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

所以当我调用:

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

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


当前回答

斯威夫特3

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

如果视图。setcontenttoffset不起作用。

使用:

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

其他回答

这是代码ScrollTableView到顶部编程

迅速:

self.TableView.setContentOffset(CGPointMake(0, 1), animated:true)

在斯威夫特

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

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

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

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

这是一个简单的UIScrollView扩展的例子,你可以在你的应用程序的任何地方使用。

1)首先你应该创建一个包含滚动方向的枚举:

enum ScrollDirection {
    case top, right, bottom, left

    func contentOffsetWith(_ scrollView: UIScrollView) -> CGPoint {
        var contentOffset = CGPoint.zero
        switch self {
            case .top:
                contentOffset = CGPoint(x: 0, y: -scrollView.contentInset.top)
            case .right:
                contentOffset = CGPoint(x: scrollView.contentSize.width - scrollView.bounds.size.width, y: 0)
            case .bottom:
                contentOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
            case .left:
                contentOffset = CGPoint(x: -scrollView.contentInset.left, y: 0)
            }
        return contentOffset
    }
}

2)然后添加扩展到UIScrollView:

extension UIScrollView {
    func scrollTo(direction: ScrollDirection, animated: Bool = true) {
        self.setContentOffset(direction.contentOffsetWith(self), animated: animated)
    }
}

3)就是这样!现在你可以使用它:

myScrollView.scrollTo(.top, animated: false)

这个滚动绑定到tableView的内容大小,它看起来比滚动到CGPoint.zero更自然

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

迅速:

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

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

tableView.scrollToTop(animated: true)