在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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];
有其他方法滚动到表视图的顶部吗?
当前回答
我发现强迫UITableViewController在iPhone、iPad和macCatalyst (macOS)下滚动到顶部的最简单方法如下:
准备返回0从[tableView:numberOfRowsInSection:] 电话(自我。tableView reloadData] 电话(自我。tableView layoutIfNeeded] 准备从[tableView:numberOfRowsInSection:]中返回实际的行数 电话(自我。tableView reloadData]
其他回答
如果你想在表格中移动滚动动画,请使用此代码。滚动移动到顶部的动画在0.5秒。
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[_tableContent scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
[UIView commitAnimations];
对于具有contentInset的表,将内容偏移量设置为CGPointZero将不起作用。它会滚动到内容顶部,而不是滚动到桌面顶部。
将内容嵌入考虑在内会产生这样的结果:
[tableView setContentOffset:CGPointMake(0, -tableView.contentInset.top) animated:NO];
注意:此答案不适用于iOS 11及更高版本。
我更喜欢
[mainTableView setContentOffset:CGPointZero animated:YES];
如果你在你的表格视图中有一个top inset,你必须减去它:
[mainTableView setContentOffset:CGPointMake(0.0f, -mainTableView.contentInset.top) animated:YES];
添加到已经说过的,你可以创建一个扩展(Swift)或类别(Objective C),使这在未来更容易:
迅速:
extension UITableView {
func scrollToTop(animated: Bool) {
setContentOffset(CGPointZero, animated: animated)
}
}
任何时候你想要滚动任何给定的tableView到顶部,你可以调用以下代码:
tableView.scrollToTop(animated: true)
Swift 4通过扩展,处理空表视图:
extension UITableView {
func scrollToTop(animated: Bool) {
self.setContentOffset(CGPoint.zero, animated: animated);
}
}