I have a UIScrollView with paging and AutoLayout working perfectly fine. Here is my set up:
UIView // Main view
|---> Dummy UIView // See below
|---> UIScrollView
|---> Content UIView
|---> Page 1 Container
|---> Page 2 Container
The constraints I used are
Dummy UIView -> Parent UIView
is whatever I want the size of the paging scrollview to be, and UIScrollView -> 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 a UIScrollView
which completely fills the dummy UIView
.
Refer to the Technote from Apple for AutoLayout and UIScrollViews
: https://developer.apple.com/library/content/technotes/tn2154/_index.html
The 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 the UIScrollView
to (0,0,0,0). The exact values don't really matter since all you are telling the UIScrollView
is that this is the view to get the contentSize
from.
At this point Xcode will complain that Content View
has no intrinsic size. And here is the trick: This is where we use the Dummy UIView
that we created above. The size of the Dummy UIView
is precisely the size of each page in the UIScrollView
.
So we set the height of Content UIView
equal to height of Dummy UIView
and the width of the Content UIView
equal to the number of pages times the width of the Dummy 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 set Paging Enabled
to yes on your UIScrollView
and voila you have paging in a UIScrollView
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…