在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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];
有其他方法滚动到表视图的顶部吗?
当前回答
在iOS 11上,使用adjuststedcontentinset可以在通话状态栏可见或不可见的两种情况下正确地滚动到顶部。
if (@available(iOS 11.0, *)) {
[tableView setContentOffset:CGPointMake(0, -tableView.adjustedContentInset.top) animated:YES];
} else {
[tableView setContentOffset:CGPointMake(0, -tableView.contentInset.top) animated:YES];
}
迅速:
if #available(iOS 11.0, *) {
tableView.setContentOffset(CGPoint(x: 0, y: -tableView.adjustedContentInset.top), animated: true)
} else {
tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true)
}
其他回答
UITableView是UIScrollView的子类,所以你也可以使用:
[mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
Or
[mainTableView setContentOffset:CGPointZero animated:YES];
在Swift中:
mainTableView.setContentOffset(CGPointZero, animated:true)
在Swift 3及以上版本中:
mainTableView.setContentOffset(.zero, animated: true)
不使用
tableView.setContentOffset(.zero, animated: true)
它有时会不正确地设置偏移量。例如,在我的例子中,单元格实际上略高于带有安全区域嵌入的视图。不好的。
而不是使用
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
如果你需要使用Objective-C或者你仍然喜欢:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
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)
}
这似乎是多余的,因为你已经在主队列上了,但这并不是因为它序列化了动画。
这段代码让你滚动一个特定的部分顶部
CGRect cellRect = [tableinstance rectForSection:section];
CGPoint origin = [tableinstacne convertPoint:cellRect.origin
fromView:<tableistance>];
[tableinstance setContentOffset:CGPointMake(0, origin.y)];