In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section
Here is a simple example of UIScrollView extension that you can use everywhere in your app.
1) First you should create enum with possible scroll directions:
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) Then add extension to UIScrollView:
extension UIScrollView {
func scrollTo(direction: ScrollDirection, animated: Bool = true) {
self.setContentOffset(direction.contentOffsetWith(self), animated: animated)
}
}
3) Thats it! Now you can use it:
myScrollView.scrollTo(.top, animated: false)
This scroll bind to the tableView's content size and it looks more natural than scroll to CGPoint.zero