在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是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]

其他回答

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)

如果你需要使用Objective-C或者你仍然喜欢:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

迅速:

tableView.setContentOffset(CGPointZero, animated: true)

斯威夫特3

tableView.setContentOffset(CGPoint.zero, animated: true)

如果视图。setcontenttoffset不起作用。

使用:

tableView.beginUpdates()
tableView.setContentOffset(CGPoint.zero, animated: true)
tableView.endUpdates()

使用contenttoffset不是正确的方法。这样会更好,因为这是表视图的自然方式

tableView.scrollToRow(at: NSIndexPath.init(row: 0, section: 0) as IndexPath, at: .top, animated: true)