【问题标题】:UITableView, UICollectionView scroll to topUITableView、UICollectionView 滚动到顶部
【发布时间】:2018-11-02 04:14:18
【问题描述】:

当您点击屏幕顶部时,UITableView 和 UICollectionView 能够滚动到顶部。我可以从代码中调用此操作吗?或者有没有其他方法可以滚动到 UITableView / UICollectionView 的顶部?

我尝试了 scrollToRow 功能,表格滚动到顶部,但导航栏标题仍然很小。我想让它像加载 viewController 一样大的导航栏标题。

【问题讨论】:

  • 只设置tableView/scrollView.setContentOffset(.zero, animated:true/false)
  • @Stiv 与 scrollToRow 有同样的问题
  • @AhmadF 我看到了这篇文章,但我没有找到解决方案。每次尝试时,我仍然遇到类似 scrollToRow 的问题。
  • 您可能需要将其视为 滚动视图 而不是表格视图,不要滚动到一行,尝试滚动到顶部内容大小...

标签: ios swift uitableview


【解决方案1】:

你可以这样做:

tableView.scrollView.scroll(to: .top)
collectionView.scrollView.scroll(to: .top)

...使用允许多个不同滚动位置的以下扩展:

extension UIScrollView {
    enum Position {
        case top
        case center
        case bottom
    }
    /// Scrolls scroll view to y position passed, animated
    func scroll(to position: Position, animated: Bool = true) {
        switch position {
        case .top:
            self.setContentOffset(CGPoint(x: 0, y: -contentInset.top), animated: animated)
        case .center:
            self.setContentOffset(CGPoint(x: 0, y: contentSize.height/2-self.frame.height/2), animated: animated)
        case .bottom:
            self.setContentOffset(CGPoint(x: 0, y: contentSize.height-self.frame.height), animated: animated)
        }
    }
    /// Scrolls scroll view to y value passed, animated
    func scroll(to position: CGFloat, animated: Bool = true) {
        self.setContentOffset(CGPoint(x: 0, y: position), animated: animated)
    }

    /// Scrolls scroll view by y value passed, animated
    func scroll(by position: CGFloat, animated: Bool = true) {
        self.setContentOffset(CGPoint(x: 0, y: self.contentOffset.y + position), animated: animated)
    }

    func scroll(to view: UIView, animated: Bool = true) {
        self.setContentOffset(CGPoint(x: 0, y: view.frame.maxY), animated: animated)
    }
}

【讨论】:

    【解决方案2】:

    使用下面的行:

    tableView.setContentOffset(.zero, animated: true)
    

    【讨论】:

    • 与scrollToRow函数相同的问题
    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2016-09-04
    • 1970-01-01
    • 2014-10-20
    • 2013-03-24
    • 2015-06-01
    相关资源
    最近更新 更多