g M
g M

Reputation: 1

Xamarin Forms - ScrollView How to check if you scroll to the bottom

private void scrollView_Scrolled(object sender, ScrolledEventArgs e) {
    OnScroll(e.ScrollY);
    var CurrentHeight = scrollView.Bounds.Height + scrollView.ScrollY + scrollView.Padding.VerticalThickness;
    var ContentHeight = scrollView.ContentSize.Height;

    Debug.WriteLine("计算当前高度:" + CurrentHeight + "|" + "内容区域总高度:" + ContentHeight + "|" + "滚动条Y:" + e.ScrollY + "|" + "当前可视区域高度:" + scrollView.Bounds.Height);

    if (scrollView.Height == e.ScrollY) {

    }
    OnScrollEnd();
}

I want to check if it's scrolled to the bottom but the code results aren't satisfactory to me CurrentHeight(2716.38095238095)!=ContentHeight(2717.2380952381)

Although they are close but not the same, why?

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="BookApp.Views.ChapterPageDetail"
             Title="{Binding Name}">


    <ScrollView x:Name="scrollView" Padding="0" Scrolled="scrollView_Scrolled" >
        <StackLayout x:Name="stackLayout" Padding="10">
            <Label Text="{Binding Content}" TextColor="#070707"/>
            <Button Text="Next chapter" Clicked="Button_Clicked"></Button>
            <StackLayout.GestureRecognizers>
                <SwipeGestureRecognizer Direction="Left" Swiped="OnSwipedLeft"/>
                <SwipeGestureRecognizer Direction="Right" Swiped="OnSwipedRight"/>
            </StackLayout.GestureRecognizers>
        </StackLayout>
    </ScrollView>
</ContentPage>

Upvotes: 0

Views: 2353

Answers (1)

Nick Kovalsky
Nick Kovalsky

Reputation: 6462

This one works for me perfectly, both values match at the end of the scroll:

 private void ScrollView_OnScrolled(object sender, ScrolledEventArgs e)
        {
            var scrollView = sender as ScrollView;
            try
            {
                var contentSize = scrollView.ContentSize.Height;
                var contentSizeCheck = ((View) scrollView.Children[0]).Height; //for fun

                var maxPos = contentSize - scrollView.Height;

                Debug.WriteLine($"Scrolled to pos {e.ScrollY}, max: {maxPos}");
            }
            catch
            {

            }
        }

Also not sure if the following is affecting you somewhere but please be aware that on iOS there's some kind of bug that ScrollView tends to set its position sometimes to a negative value, this can be fixed with a renderer in the

protected override void OnElementChanged(VisualElementChangedEventArgs e)

set a cute ((ScrollView)e.NewElement).SetScrolledPosition(0, 0); this will disable the bouncing though..

Upvotes: 2

Related Questions