Skip to content

Instantly share code, notes, and snippets.

@BrychanOdlum
Created January 21, 2020 22:07
Show Gist options
  • Save BrychanOdlum/86f8e3a7ce4c59bb459d79599781ca55 to your computer and use it in GitHub Desktop.
Save BrychanOdlum/86f8e3a7ce4c59bb459d79599781ca55 to your computer and use it in GitHub Desktop.
UIScrollView scroll target view to centre
extension UIScrollView {
func scrollToCenter(_ targetView: UIView) {
let viewportHeight = self.frame.height - self.contentInset.bottom
let posInViewport = targetView.frame.origin.y + (targetView.frame.height / 2) - self.contentOffset.y
let posDelta = (viewportHeight / 2) - posInViewport
var newYOffset = self.contentOffset.y - posDelta
if newYOffset < 0 {
newYOffset = 0
} else if newYOffset > self.subviews[0].frame.height - viewportHeight {
newYOffset = self.subviews[0].frame.height - viewportHeight
}
self.setContentOffset(CGPoint(x: self.contentOffset.x, y: newYOffset), animated: true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment