UITableView, UICollectionView 滚动到顶部



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

我尝试了scrollToRow功能,表格滚动到顶部,但导航栏标题仍然很小。我想让它像加载视图控制器一样作为大导航栏标题。

你可以做这样的事情:

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

使用以下行:

tableView.setContentOffset(.zero, animated: true)

最新更新