Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift

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 hierarchy.

The UIScrollView move so that the child view is at the top of the UIScrollView (either animated or not)

like image 603
dyson returns Avatar asked Aug 18 '16 12:08

dyson returns


1 Answers

Here's an extension I ended up writing.

Usage:

Called from my viewController, self.scrollView is an outlet to the UIScrollView and self.commentsHeader is a view within it, near the bottom:

self.scrollView.scrollToView(self.commentsHeader, animated: true) 

Code:

You only need the scrollToView method, but leaving in scrollToBottom / scrollToTop methods too as you'll probably need those too, but feel free to delete them.

extension UIScrollView {      // Scroll to a specific view so that it's top is at the top our scrollview     func scrollToView(view:UIView, animated: Bool) {         if let origin = view.superview {             // Get the Y position of your child view             let childStartPoint = origin.convertPoint(view.frame.origin, toView: self)             // Scroll to a rectangle starting at the Y of your subview, with a height of the scrollview             self.scrollRectToVisible(CGRect(x:0, y:childStartPoint.y,width: 1,height: self.frame.height), animated: animated)         }     }      // Bonus: Scroll to top     func scrollToTop(animated: Bool) {         let topOffset = CGPoint(x: 0, y: -contentInset.top)         setContentOffset(topOffset, animated: animated)     }      // Bonus: Scroll to bottom     func scrollToBottom() {         let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)         if(bottomOffset.y > 0) {             setContentOffset(bottomOffset, animated: true)         }     }  } 
like image 99
dyson returns Avatar answered Oct 11 '22 21:10

dyson returns