0

UITableView and UICollectionView is able to scroll to top when you tap on top of the screen. Am I able to call this action from code? Or is there any other way to scroll to top of UITableView / UICollectionView?

I tried scrollToRow function, table scrolls to top, but navbar title remains small. I want to have it as big nav bar title like on load of viewController.

Lifeplus
  • 531
  • 2
  • 9
  • 22

2 Answers2

2

You can do something like this:

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

...using the following extension that allows for several different scroll positions:

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)
    }
}
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
1

use below line:

tableView.setContentOffset(.zero, animated: true)
Moayad Al kouz
  • 1,342
  • 1
  • 9
  • 19