Search code examples
ioscocoa-touchuiscrollviewios7

In iOS 7, how to scroll to the top of a UIScrollView when using a translucent UINavigationBar?


In iOS 6, you could scroll to the top of a UIScrollView using:

[scrollView setContentOffset:CGPointZero animated:YES];

If you use that code in iOS 7 with a translucent navigation bar, you get a result that is technically correct, but not user friendly. The top of the scroll view will be positioned to the origin of the screen.

enter image description here

How would I position the top of the scroll view to the bottom of the navigation bar instead? I'm looking for a solution that is not hardcoded, because in my application, sometimes the status bar and navigation bar can be hidden. Also, I would like to keep the translucent effect instead of copping out and doing self.edgesForExtendedLayout = UIRectEdgeNone.


Solution

  • Instead of using hard-coded values, use the new API:

    [self.scrollView setContentInset:UIEdgeInsetsMake(self.topLayoutGuide.length, 0, self.bottomLayoutGuide.length, 0)];
    

    You are setting the content insets of the scroll view to top and bottom layout guides. So if you have a navigation bar that is 44 points and a status bar of 20 points and no status bar, it will be 64 points top (in portrait) and 0 points bottom.

    You should do this in viewDidLayoutSubviews.