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

所以当我调用:

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

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


当前回答

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

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

其他回答

这是唯一适合我的代码片段

斯威夫特4:

    tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
    tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
    tableView.setContentOffset(CGPoint(x: 0, y: -70), animated: true)

P.S. 70是我的头和表格视图单元格的高度

在斯威夫特

your row = selectioncellRowNumber 你的section如果你有= selectionNumber如果你没有set为零

/ / UITableViewScrollPosition。中间或底部或顶部

var lastIndex = NSIndexPath(forRow:  selectioncellRowNumber, inSection: selectionNumber)
self.tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

迅速:

tableView.setContentOffset(CGPointZero, animated: true)

如果你不想要滚动,你可以启动和停止滚动动画,只要你启动它。

    $('document').ready(function() {
    $("html, body").animate({ scrollTop: 0 }, 500);
    return true;
    });

此外,为了使'x'和'y'的值动画化,传入0,0将立即将页面滚动到左上角。

window.scrollTo(x, y);

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

迅速:

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

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

tableView.scrollToTop(animated: true)