PIXEL
DOCK

I like the smell of Swift in the morning…

UIScrollView and Auto Layout.

Posted: | Author: | Filed under: iOS, Swift | Tags: , , | 9 Comments »

Some people still seem to struggle when it comes to using Apple’s Auto Layout in a UIScrollView. There are a lot of questions on StackOverflow like “Why is my UIScrollView not scrolling when using AutoLayout?”

So here is a short explanation on how to use Auto Layout with a UIScrollView that should scroll vertically:

There are just a few things you have to take care of:

1. The topmost subview must have a top constraint with the UIScrollView
2. All other subviews must have a top constraint with the bottom constraint of the subview above them
3. The bottommost subview must have a bottom constraint with the UIScrollView

To ensure that the UIScrollView only scrolls vertically you have to make sure that its subviews don’t become wider than the UIScrollView.

Do not rely on left and right constraints to define the width of a subview. If for example you have a UILabel that has a lot of text and should break into several lines, it just won’t, even if you set its numberOfLines property to 0. That’s because the UIScrollView will give it enough space by allowing horizontal scrolling. So if you just set a left and right constraint on the UILabel the UIScrollView will scroll horizontal and the label will be very wide and have only 1 line.

Instead you should define a left and a width constraint. Set the width constraint to the width of the UIScrollView and the UILabel will not become wider than the UIScrollView. It will wrap into multiple lines instead.

If you follow those steps you don’t have to set the UIScrollView’s contentSize property any more to make the UIScrollView scroll. Auto Layout will handle that for you.

To make it more clear, here is an image with the constraints that you have to set:

scrollview_al

If you are using Masonry or SnapKit here is a code example on how to set the constraints programmatically:

topView.snp_makeConstraints { (make) -> Void in
    make.top.equalTo(0)
    make.left.equalTo(0)
    make.width.equalTo(scrollView)
}
label1.snp_makeConstraints { (make) -> Void in
    make.top.equalTo(topView.snp_bottom)
    make.left.equalTo(0)
    make.width.equalTo(scrollView)
}
label2.snp_makeConstraints { (make) -> Void in
   make.top.equalTo(label1.snp_bottom)
   make.left.equalTo(0)
   make.width.equalTo(scrollView)
}
label3.snp_makeConstraints { (make) -> Void in
    make.top.equalTo(label2.snp_bottom)
    make.left.equalTo(0)
    make.width.equalTo(scrollView)
    make.bottom.equalTo(0)
}