There are plenty of answers regarding scroll views with autolayout and plenty about scrollview paging, but I can't find a single thing that addresses both.
I'm not trying to do anything fancy…just 7
full-screen image views that I would like to scroll horizontally with paging, but for the sake of simplicity (ha!), I decided to attempt it all right in the storyboard.
The controller is set to freeform size with a width of 2240 (320*7)
. I then set it up the way Apple suggests for autolayout…
UIScrollview
/-----UIView
/----------Content (7 image views)
The scrollview has 0/0/0/0
constraints to all edges, as does the UIView inside.
When Paging Enabled is off, it behaves beautifully – exactly as expected. But once I turn Paging on, a swipe makes the view go crazy, scrolling the entire 2240
width, and then bouncing back and eventually landing on the proper page.
I know I have the tried-and-true option of just scrapping it all and doing it programmatically, but my stubbornness wants to figure this out. It must be possible!
Best Answer
I have a UIScrollView with paging and AutoLayout working perfectly fine. Here is my set up:
The constraints I used are
Dummy UIView -> Parent UIView
is whatever I want the size of the paging scrollview to be, andUIScrollView -> Dummy UIView
is (0,0,0,0) on all sides. This is just regular auto layout stuff which creates a dummy UIView where I want to put the scrollview and aUIScrollView
which completely fills the dummyUIView
.Refer to the Technote from Apple for AutoLayout and
UIScrollViews
: https://developer.apple.com/library/content/technotes/tn2154/_index.htmlThe content inside the scrollview has to have an intrinsic size. It cannot rely on the scrollview to get its size.
As indicated in the TechNote, set the constraints from all four sides of the
Content View
to theUIScrollView
to (0,0,0,0). The exact values don't really matter since all you are telling theUIScrollView
is that this is the view to get thecontentSize
from.At this point Xcode will complain that
Content View
has no intrinsic size. And here is the trick: This is where we use theDummy UIView
that we created above. The size of theDummy UIView
is precisely the size of each page in theUIScrollView
.So we set the height of
Content UIView
equal to height ofDummy UIView
and the width of theContent UIView
equal to the number of pages times the width of theDummy UIView
using AutoLayout. (For the later change the multiplier in the constraint to be the number of pages).Now create pages inside the
Content UIView
as you normally would and setPaging Enabled
to yes on yourUIScrollView
and voila you have paging in aUIScrollView
using AutoLayout.I've tested this in IOS 6, 7 & 8.
Update:
Here is a sample project with this setup as requested: https://github.com/kostub/PagingScrollView