简体   繁体   English

如何重置 UITableView 的滚动位置?

[英]How to reset the scroll position of a UITableView?

I would like to completely reset the scroll position of a UITableView, so that every time I open it, it is displaying the top-most items.我想完全重置 UITableView 的滚动位置,以便每次打开它时,它都会显示最顶部的项目。 In other words, I would like to scroll the table view to the top every time it is opened.换句话说,我想在每次打开表格视图时将它滚动到顶部。

I tried using the following piece of code, but it looks like I misunderstood the documentation:我尝试使用以下代码段,但看起来我误解了文档:

- (void)viewWillAppear:(BOOL)animated {
    [tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:NO];
}

Is this the wrong approach here?这是错误的方法吗?

August got the UITableView-specific method. August 得到了 UITableView 特有的方法。 Another way to do it is:另一种方法是:

[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

This method is defined in UIScrollView, the parent class to UITableView.该方法定义在 UIScrollView 中,UITableView 的父类。 The above example tells it to scroll to the 1x1 box at 0,0 - the top left corner, in other words.上面的例子告诉它滚动到 0,0 处的 1x1 框 - 换句话说,左上角。

The method you're using scrolls to (as the method name implies) the nearest selected row.您使用的方法滚动到(正如方法名称所暗示的)最近的选定行。 In many cases, this won't be the top row.在许多情况下,这不会是第一行。 Instead, you want to use either相反,您想使用

scrollToRowAtIndexPath:atScrollPosition:animated:

or或者

selectRowAtIndexPath:animated:scrollPosition:

where you use the index path of the row you want to scroll to.您使用要滚动到的行的索引路径的位置。 The second method actually selects a row, the first method simply scrolls to it.第二种方法实际上选择一行,第一种方法只是滚动到它。

What I ended up doing was this:我最终做的是这样的:

Swift 4斯威夫特 4

self.tableView.contentOffset = CGPoint.zero
DispatchQueue.main.async {
    self.tableView.reloadData()
}

迅速:

self.tableView.scrollRectToVisible(CGRect.zero, animated: false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM