Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Last active May 8, 2023 03:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgr-ksmt/3331bf38dc821eecdc695465347ddee3 to your computer and use it in GitHub Desktop.
Save sgr-ksmt/3331bf38dc821eecdc695465347ddee3 to your computer and use it in GitHub Desktop.
UIScrollView: scroll top/bottom/left/right perfectly! http://blog.sgr-ksmt.org/2016/11/11/uiscrollview_scroll_extension/
extension UIScrollView {
public enum ScrollDirection {
case top
case bottom
case left
case right
}
public func scroll(to direction: ScrollDirection, animated: Bool) {
let offset: CGPoint
switch direction {
case .top:
offset = CGPoint(x: contentOffset.x, y: -contentInset.top)
case .bottom:
offset = CGPoint(x: contentOffset.x, y: max(-contentInset.top, contentSize.height - frame.height + contentInset.bottom))
case .left:
offset = CGPoint(x: -contentInset.left, y: contentOffset.y)
case .right:
offset = CGPoint(x: max(-contentInset.left, contentSize.width - frame.width + contentInset.right), y: contentOffset.y)
}
setContentOffset(offset, animated: animated)
}
}
@sgr-ksmt
Copy link
Author

sgr-ksmt commented Nov 11, 2016

Usage

tableView.scroll(to: .bottom, animated: true)
collectionView.scroll(to: .top, animated: false)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment