在表格视图中,我必须滚动到顶部。但我不能保证第一个对象是section 0,第0行。可能我的表视图将从第5节开始。

所以当我调用:

[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];

有其他方法滚动到表视图的顶部吗?


当前回答

我更喜欢下面的,因为它考虑到一个插图。如果没有插入,它仍然会滚动到顶部,因为插入将是0。

tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true)

其他回答

最好不要使用NSIndexPath(空表),也不要假设顶点是CGPointZero(内容嵌入),这就是我使用的-

[tableView setContentOffset:CGPointMake(0.0f, -tableView.contentInset.top) animated:YES];

希望这能有所帮助。

在Swift-3中:

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

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

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

我发现强迫UITableViewController在iPhone、iPad和macCatalyst (macOS)下滚动到顶部的最简单方法如下:

准备返回0从[tableView:numberOfRowsInSection:] 电话(自我。tableView reloadData] 电话(自我。tableView layoutIfNeeded] 准备从[tableView:numberOfRowsInSection:]中返回实际的行数 电话(自我。tableView reloadData]

我必须把状态栏和导航栏的和乘以-1 *,因为它离屏幕有那么高,

self.tableView.setContentOffset(CGPointMake(0 , -1 * 
  (self.navigationController!.navigationBar.height +  
  UIApplication.sharedApplication().statusBarFrame.height) ), animated:true)