在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是section 0,第0行。可能我的表视图将从第5节开始。
所以当我调用:
[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
有其他方法滚动到表视图的顶部吗?
在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是section 0,第0行。可能我的表视图将从第5节开始。
所以当我调用:
[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
有其他方法滚动到表视图的顶部吗?
当前回答
最好不要使用NSIndexPath(空表),也不要假设顶点是CGPointZero(内容嵌入),这就是我使用的-
[tableView setContentOffset:CGPointMake(0.0f, -tableView.contentInset.top) animated:YES];
希望这能有所帮助。
其他回答
这是代码ScrollTableView到顶部编程
迅速:
self.TableView.setContentOffset(CGPointMake(0, 1), animated:true)
这段代码让你滚动一个特定的部分顶部
CGRect cellRect = [tableinstance rectForSection:section];
CGPoint origin = [tableinstacne convertPoint:cellRect.origin
fromView:<tableistance>];
[tableinstance setContentOffset:CGPointMake(0, origin.y)];
Swift 5, iOS 13
我知道这个问题已经有很多答案了,但从我的经验来看,这个方法总是有效的:
let last = IndexPath(row: someArray.count - 1, section: 0)
tableView.scrollToRow(at: last, at: .bottom, animated: true)
如果你正在处理动画(比如键盘)或某些异步任务,这尤其正确——其他答案通常会滚动到底部。如果由于某种原因,这不能让你一直到底部,这几乎肯定是因为竞争动画,所以解决方法是将这个动画分派到主队列的末尾:
DispatchQueue.main.async {
let last = IndexPath(row: self.someArray.count - 1, section: 0)
self.tableView.scrollToRow(at: last, at: .bottom, animated: true)
}
这似乎是多余的,因为你已经在主队列上了,但这并不是因为它序列化了动画。
我更喜欢下面的,因为它考虑到一个插图。如果没有插入,它仍然会滚动到顶部,因为插入将是0。
tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true)
如果你需要使用Objective-C或者你仍然喜欢:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];