UIScrollView doesn't use autolayout constraints UIScrollView doesn't use autolayout constraints objective-c objective-c

UIScrollView doesn't use autolayout constraints


The relationship between UIScrollView and auto layout is different from other aspects of auto layout. Basically, if simple auto layout were allowed to operate, nothing would scroll. For example, if a subview of the scroll view were pinned in the normal way by a constraint to 10 points from the top of the scroll view, it would be absolutely pinned there; it would never move, no matter how the scroll view were scrolled.

To solve this problem, a UIScrollView that uses autolayout operates in a completely new way. Therefore when you say "I am using autolayout" you must prepare for things to operate very differently from before. You must either use a single scroll view subview with translatesAutoresizingMaskIntoConstraints = YES, and an explicit content size, or else everything must have translatesAutoresizingMaskIntoConstraints = NO and the content size will be deduced implicitly based on the constraints of the subviews.

This is very well explained in https://developer.apple.com/library/content/releasenotes/General/RN-iOSSDK-6_0/index.html


Very important when using auto-layout: you must pin the right and/or bottom of the last subview to the right and/or bottom of the scroll view. This is how the scroll view knows the content size. For example:

[scrollView addConstraint:[NSLayoutConstraint constraintWithItem:lastSubView                                                 attribute:NSLayoutAttributeRight                                                 relatedBy:NSLayoutRelationEqual                                                    toItem:scrollView                                                 attribute:NSLayoutAttributeRight                                                multiplier:1.0                                                  constant:0]];

My thanks to this site for providing the perfect example.

I lost hours because of this, and I hope to spare others my pain.


To get UIScrollviews to work nicely with constraints, I use this approach answered here. In that answer, I tackle how to get a vertically scrolling scrollview working that also works with device rotation. You can tweak the approach to work with horizontally scrolling scrollviews too. For scrollviews that scroll in both directions, don't add the size matching width constraint trick. But do everything else the same.