How do I make a UIScrollView scroll to the top?
[self.scrollView setContentOffset:
CGPointMake(0, -self.scrollView.contentInset.top) animated:YES];
[self.scrollView setContentOffset:CGPointZero animated:YES];
or if you want to preserve the horizontal scroll position and just reset the vertical position:
[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0)
animated:YES];
If you're doing this for iOS 7, you may have to take into account the
UIScrollView
contentInset
, unfortunately.[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, -self.scrollView.contentInset.top) animated:YES];
does the job for meI was able to scroll to the top, right below the navigation and status bar.
[scrollView setContentOffset:CGPointMake(0, -scrollView.contentInset.top) animated:YES];
It works in iOS 6 & 7This didn't work for me, probably because I'm doing something crazy with an inverted view in sprite kit. But if anyone else is as crazy as me - and your scrollview is at the bottom by default - this will scroll it to the top:
[scrollView setContentOffset:CGPointMake(0, scrollView.contentSize.height-scrollView.frame.size.height) animated:YES];
Late-in-the-day comment: you should adjust for the content inset regardless of OS version. iOS 7 happens to use it for allowing scroll content below the status bar but it's always been exposed as a property, so always been potentially used by somebody.
For iOS 11+, Jakub Truhlář's answer below using adjustedContentInset was helpful, at least in my case.