在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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)
}
其他回答
我使用tabBarController,我有几个节在我的表视图在每个选项卡,所以这是我最好的解决方案。
extension UITableView {
func scrollToTop(){
for index in 0...numberOfSections - 1 {
if numberOfSections > 0 && numberOfRows(inSection: index) > 0 {
scrollToRow(at: IndexPath(row: 0, section: index), at: .top, animated: true)
break
}
if index == numberOfSections - 1 {
setContentOffset(.zero, animated: true)
break
}
}
}
}
如果你想在表格中移动滚动动画,请使用此代码。滚动移动到顶部的动画在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];
不使用
tableView.setContentOffset(.zero, animated: true)
它有时会不正确地设置偏移量。例如,在我的例子中,单元格实际上略高于带有安全区域嵌入的视图。不好的。
而不是使用
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
最好不要使用NSIndexPath(空表),也不要假设顶点是CGPointZero(内容嵌入),这就是我使用的-
[tableView setContentOffset:CGPointMake(0.0f, -tableView.contentInset.top) animated:YES];
希望这能有所帮助。
在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)
}