无法将ListView滚动到iOS顶部?

时间:2018-11-20 14:50:02

标签: listview xamarin xamarin.forms xamarin.ios

在Xamarin Forms 3.3上,我无法将ListView滚动到iOS顶部。

我尝试:Scrolling to start of Xamarin Forms ListView with header 但是无法将滚动ListView设置为顶部。 这是我的代码:

在iOS控件上:

public class ExtListViewRenderer : ListViewRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<ListView> e) => iOS.Control.Logger.InvokeAction(() =>
    {
        base.OnElementChanged(e);

        if (!(e.NewElement is ExtListView extListView) || Control == null)
            return;

        extListView.EventScrollToTop += OnScrollToTop;
    });

    public void OnScrollToTop(object sender, EventArgs eventArgs)
    {
        Control.ScrollRectToVisible(new CoreGraphics.CGRect(0, 0, 1, 1), true);
    }

}

在班级控制下:

public class ExtListView : ListView
{
    public event EventHandler EventScrollToTop;

    /// <summary>
    /// Scroll LisView To Top
    /// </summary>
    /// <param name="animate"></param>
    public void ScrollToTop(bool animate = true)
    {
        //bool animate is not used at this stage, it's always animated.
        EventScrollToTop?.Invoke(this, EventArgs.Empty);
    }
}

在.xaml视图上:

    <control:ExtListView.Behaviors>
        <common:MethodToDelegateBehavior Delegate="{Binding ScrollToTop}"
                                         DelegateType="{x:Type propertyViewModels:PropertyPageViewModel+ScrollToTopDelegate}"
                                         MethodName="ScrollToTop" />
    </control:ExtListView.Behaviors>

在页面上:

    public delegate void ScrollToTopDelegate(bool animate);
    private ScrollToTopDelegate _scrollToTop;
    public ScrollToTopDelegate ScrollToTop
    {
        get => _scrollToTop;
        set => this.RaiseAndSetIfChanged(ref _scrollToTop, value);
    }

使用方法时:

ScrollToTop?.Invoke(true);
  • 我在Android上使用它是可以的,但iOS无法使用。

2 个答案:

答案 0 :(得分:1)

我使用以下代码将ListView类滚动到特定位置。

Control.SetContentOffset(new CGPoint(Control.ContentOffset.X, y), animated);

滚动时,X通常不会更改,但是 Y 是您要更改的值。使用该代码滚动到顶部将像这样:

// You can send true for the animate property whether or not you want to see the scroll happen
Control.SetContentOffset(new CGPoint(Control.ContentOffset.X, 0), true);

答案 1 :(得分:0)

这是我的主意

  • 使用类ScrollToScrollTo)的方法ListView
  • 将重点放在ListView上的项目设置为第一项,ScrollToPositionScrollToPosition.Start

(如果要查看滚动发生,请使用animated = true

创建一个标志:ScrollToTop = true在布局.xaml中使用,该处理程序更改ListView的滚动。

您尝试一下:

 var firstItem = ((IEnumerable<object>)extListView.ItemsSource)?.FirstOrDefault();
 if (firstItem != null)
     extListView.ScrollTo(firstItem, ScrollToPosition.Start, false);

希望它可以为您提供帮助!