0

I have a ScrollView with an Editor content inside.

I'm creating a custom Editor which resizes dependant on text inside it.

        <ScrollView x:Name="sv" Grid.Row="2" HorizontalOptions="Fill" VerticalOptions="Fill" Orientation="Both"
                        HorizontalScrollBarVisibility="Always" VerticalScrollBarVisibility="Always" BackgroundColor="LightGreen">
            <local:EditorEx x:Name="ed" Margin="0" BackgroundColor="LightBlue" HorizontalOptions="Start" VerticalOptions="Start"/>
        </ScrollView>

I've successfully managed to get the editor to dynamically resize the editor based on this code placed in the renderer:

How do I size a UITextView to its content?

      void Init()
        {
            //needed for below code to work
        Control.ScrollEnabled = false;
        }

        private void Control_Changed(object sender, System.EventArgs e)
        {
            CGSize newSize = Control.SizeThatFits(new CGSize(nfloat.MaxValue, nfloat.MaxValue));
            CGRect newFrame = Control.Frame;
            newFrame.Size = new CGSize(newSize.Width, newSize.Height);
            //Control.Frame = newFrame;
  
            //this is the xamarin Editor control
            editor.WidthRequest = newSize.Width;
            editor.HeightRequest = newSize.Height;
        }

However, the ScrollView does not dynamically re-adjust according to the new editor size and hence I can't scroll to the newly added text.

How can I resolve this?

jho
  • 199
  • 1
  • 8
  • As you've seen, the ScrollView doesn't know that it should resize when the Entry content resizes. You'll have to manually set its WidthRequest and HeightRequest. Use MessagingCenter. In your custom control, Publish a message describing the editor size change. In your page that contains `sv`, Subscribe to that message, set sv.WidthRequest etc. – ToolmakerSteve Aug 20 '22 at 19:21
  • Thanks for your reply. sv.WidthRequest however will refer to the **visible** width, not the **virtual** width, which is what I need. The only reference within sv to the virtual size is **ContentSize** which is a readonly property. – jho Aug 22 '22 at 17:27
  • You are right; I was thinking about it wrong. Try `sv.ForceLayout();` – ToolmakerSteve Aug 22 '22 at 17:52
  • Looks like it's working. If you want to write an answer to this I will up-vote it. Thanks a lot! – jho Aug 23 '22 at 08:19

1 Answers1

1

To get a layout to recalculate its display, after a programmatic change that affects it, try ForceLayout:

sv.ForceLayout();

In most cases this happens automatically, but ScrollView does not realize that a change to its contents may require this.

ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196