Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms - ScrollView - ScrollToAsync to bottom not working as expected

I have a screen where it shows comment list using stack layout and scrollview. User can add one more comment and click submit would add one more comments at the end of this scroll view for Xamarin Forms - Android and iOS app. Requirement is to scroll this list up to show latest display comment element. For this, I have used below line of code but it does not scroll up till the last element but second last element. I observed it in IOS and Android both.

await scrollView.ScrollToAsync(stkMain, ScrollToPosition.End, true);

Below image would give more idea about it.

enter image description here

As shown in picture, stack Layout 3 is not visible on screen though I have used above code to scroll till end. I have to scroll up scroll view to see stack layout 3.

Expected behavior - scroll view should scroll till complete last element as displayed on screen. Kindly suggest If I am not doing it right.

One thing I forget to mention is, when I have create point at line having scrolToAsync method in debug mode. Break point hits that line and if I hit F5 would make last element visible. I am surprised to see it but it happens

like image 354
Ravi Kanasagra Avatar asked Oct 31 '17 15:10

Ravi Kanasagra


2 Answers

Remember that the rendering methods often is asynchronous, and the code behind can run before the elements are available on the rendered screen. I know that it's not the best solution, but sometimes I used to force a 300ms delay before run any visual interaction.

Try wait a short time (like 100 or 200ms) after you add new comment elements and then try scroll to the last child of your stkMain, instead.

Something like this:

// Here goes your logic to add the new comment

await Task.Delay(100);

var lastChild = stkMain.Children.LastOrDefault();
if(lastChild != null)
    scrollView.ScrollToAsync(lastChild, ScrollToPosition.MakeVisible, true);
like image 77
Diego Rafael Souza Avatar answered Nov 09 '22 20:11

Diego Rafael Souza


If you want to scroll just to bottom try

        Device.BeginInvokeOnMainThread(async () =>
        {
            // Update your children here, add more or remove.
            // todo

            if (Device.RuntimePlatform == Device.Android)
            {
                await scrollView.ScrollToAsync(0, stkMain.Height, true);
            }
            else
            {
                await Task.Delay(10); //UI will be updated by Xamarin
                await scrollView.ScrollToAsync(stkMain, ScrollToPosition.End, true);
            }

        });
like image 38
Nick Kovalsky Avatar answered Nov 09 '22 18:11

Nick Kovalsky