I have a few screens worth of content within my UIScrollView which only scrolls vertically.
I want to programmatically scroll to a view contained somewhere in it\'s
For me scrollRectToVisible() didn't work (see here), so I used setContentOffset() and calculated it myself, based on AMAN77's answer:
extension UIScrollView {
func scrollToView(view:UIView, animated: Bool) {
if let superview = view.superview {
let child = superview.convert(view.frame, to: self)
let visible = CGRect(origin: contentOffset, size: visibleSize)
let newOffsetY = child.minY < visible.minY ? child.minY : child.maxY > visible.maxY ? child.maxY - visible.height : nil
if let y = newOffsetY {
setContentOffset(CGPoint(x:0, y: y), animated: animated)
}
}
}
}
It is for a horizontal scroll view, but the same idea can be applied vertically too.