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

所以当我调用:

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

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


当前回答

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)
}

这似乎是多余的,因为你已经在主队列上了,但这并不是因为它序列化了动画。

其他回答

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

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

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

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

添加到已经说过的,你可以创建一个扩展(Swift)或类别(Objective C),使这在未来更容易:

迅速:

extension UITableView {
    func scrollToTop(animated: Bool) {
        setContentOffset(CGPointZero, animated: animated)
    }
}

任何时候你想要滚动任何给定的tableView到顶部,你可以调用以下代码:

tableView.scrollToTop(animated: true)
func scrollToTop() {
        NSIndexPath *topItem = [NSIndexPath indexPathForItem:0 inSection:0];
        [tableView scrollToRowAtIndexPath:topItem atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

调用这个函数,无论你想让UITableView滚动到顶部

在Swift 5中,非常感谢@Adrian的回答

extension UITableView{

    func hasRowAtIndexPath(indexPath: IndexPath) -> Bool {
        return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section)
    }

    func scrollToTop(_ animated: Bool = false) {
        let indexPath = IndexPath(row: 0, section: 0)
        if hasRowAtIndexPath(indexPath: indexPath) {
            scrollToRow(at: indexPath, at: .top, animated: animated)
        }
    }

}

用法:

tableView.scrollToTop()