Created
January 21, 2020 22:07
-
-
Save BrychanOdlum/86f8e3a7ce4c59bb459d79599781ca55 to your computer and use it in GitHub Desktop.
UIScrollView scroll target view to centre
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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