ios UIScrollView have a bad default contentOffset – swift

Posted on

ios UIScrollView have a bad default contentOffset – swift

I have a View inside a ScrollView inside my main View

The problem is that my scrollView have a bad default contentOffset.
His value is (0, -64) in portrait

The Apple doc says

The default value is CGPointZero.

I put this code on my controller to temporary handle it :

dispatch_async(dispatch_get_main_queue(), {
  self.scrollView.setContentOffset(CGPointZero, animated:false)

Why my contentOffset have not the good default value ?

Solution :

It’s probably an issue with the view insets.

On your XIB/Storyboard for your view controller, make sure to uncheck the Adjust Scroll View Insets

uncheck the Adjust Scroll View Insets

or in your code add self.automaticallyAdjustsScrollViewInsets = false

Swift 4.2+

scrollView.contentInsetAdjustmentBehavior = .never

I found the explanation on this website:

Handling navigation bar on top of our scroll view

The iOS 7 view of course comes with the new look where scroll views go under the navigation bar for a nice effect. One can change the scroll view’s contentInset manually to cover for the portion of it that is being overlapped at the top, but doing so manually is tedious and not fun. I was very thrilled to discover handling it should come at no cost if my ViewController has automaticallyAdjustsScrollViewInsets set to YES.

This didn’t work for me out of the box since it turns out for the magic to happen the scroll view has to be the first subview of your ViewController’s UIView. I had to reorder my subviews and then the magic started rolling.

Leave a Reply

Your email address will not be published. Required fields are marked *