如何将TableView滚动至顶部?TableView无ListView的ScrollTo方法
如何实现TableView滚动至顶部?
确实,TableView不像ListView那样自带现成的ScrollTo方法,刚碰到这个需求的时候我也卡了一下!不过不同平台都有对应的解决方案,我给你整理几个常见场景的实现方式:
iOS(UITableView)
UIKit里的UITableView其实有专门的滚动API,直接调用就能快速滚到顶部:
// 滚动到第0组第0行,带动画效果 tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true) // 不需要动画的话,把animated参数改成false即可 // tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
注意:如果你的TableView可能为空(没有任何行或组),建议用下面的方式直接设置偏移量,避免索引越界异常:
// 考虑导航栏/状态栏的内边距,确保滚到真正的顶部 tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true)
Xamarin.Forms TableView
Xamarin.Forms的TableView没有原生的滚动到顶部方法,这时候需要借助自定义渲染器来实现:
第一步:共享项目定义自定义TableView
先创建一个继承自TableView的自定义控件,添加滚动命令:
public class CustomTableView : TableView { public ICommand ScrollToTopCommand { get; set; } }
第二步:iOS端渲染器
[assembly: ExportRenderer(typeof(CustomTableView), typeof(CustomTableViewRenderer))] namespace YourAppNamespace.iOS { public class CustomTableViewRenderer : TableViewRenderer { protected override void OnElementChanged(ElementChangedEventArgs<TableView> e) { base.OnElementChanged(e); if (Control != null && e.NewElement is CustomTableView customTableView) { customTableView.ScrollToTopCommand = new Command(() => { // 设置偏移量到顶部,考虑内边距 Control.SetContentOffset(new CGPoint(0, -Control.ContentInset.Top), true); }); } } } }
第三步:Android端渲染器
[assembly: ExportRenderer(typeof(CustomTableView), typeof(CustomTableViewRenderer))] namespace YourAppNamespace.Droid { public class CustomTableViewRenderer : TableViewRenderer { protected override void OnElementChanged(ElementChangedEventArgs<TableView> e) { base.OnElementChanged(e); if (Control != null && e.NewElement is CustomTableView customTableView) { customTableView.ScrollToTopCommand = new Command(() => { // 平滑滚动到第一个位置 Control.SmoothScrollToPosition(0); }); } } } }
之后在页面里直接调用customTableView.ScrollToTopCommand.Execute(null);就能触发滚动到顶部了。
WPF DataGrid(类TableView场景)
如果是WPF中用DataGrid做表格展示,滚动到顶部的方式很直接:
// 带动画滚动到第一项 if (dataGrid.Items.Count > 0) { dataGrid.ScrollIntoView(dataGrid.Items[0]); } // 无动画直接跳转到顶部 dataGrid.ScrollViewer.ScrollToTop();
同样要注意先判断Items是否为空,避免空引用异常。
内容的提问来源于stack exchange,提问作者Ian Warburton
相关产品推荐
相关产品推荐

