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

所以当我调用:

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

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


当前回答

scrollToRow解决方案,它修复了空TableView(需要搜索)的问题。

import UIKit

extension UITableView {
    
    public func scrollToTop(animated: Bool = false) {
        if numberOfRows(inSection: 0) > 0 {
            scrollToRow(
                at: .init(row: 0, section: 0),
                at: .top,
                animated: animated
            )
        }
    }
    
}

其他回答

迅速:

如果你没有tableView头文件:

tableView.setContentOffset(CGPointMake(0,  UIApplication.sharedApplication().statusBarFrame.height ), animated: true)

如果有:

tableView.setContentOffset(CGPointMake(0, -tableViewheader.frame.height   + UIApplication.sharedApplication().statusBarFrame.height ), animated: true)

在Swift-3中:

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

使用这段代码在swift中实现UITableview:

var cell = tableView.dequeueReusableCellWithIdentifier(“cell”)
if cell == nil {
    cell = UITableViewCell(style: .Value1, reuseIdentifier: “cell”)
}

在斯威夫特

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

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

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

斯威夫特4:

这个方法非常有效:

//self.tableView.reloadData() if you want to use this line remember to put it before 
let indexPath = IndexPath(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)