Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a UIScrollView not scrolling vertically (using Auto Layout)?

Screenshot

My view hierarchy is

UIView

       UIScrollView

           UIView1

               -->UIView1.1

               -->UILabel

               -->UILabel

               -->UILabel

               -->UILabel  (bottom)

I am using Autolayout. I have tried all the ways and searched a lot. I did connect the bottom UILabel to the Bottom Layout of the UIView1 and set its priority to the 750 (the lowest of all). I have almost tried everything which is said on this forum and everywhere because everybody is saying same thing.

I am also adding the one view dynamically in UIView1.1. I have no idea why this is not working. Scrollview is not scrolling properly. Please help me. I am stuck on this for 3 days.

like image 548
Nav Avatar asked Nov 28 '22 06:11

Nav


1 Answers

To make this work is actually quite easy. You do not need to put all labels into an extra view. And you do not have to set the contentSize yourself. Auto Layout will do that for you.

You just have to make sure to have the following things:

  1. Each label and the view on top of the labels have to have a width constraint that is set to the width of the scroll view and a left constraint with value 0 (or any padding you might want to add)
  2. The view on top needs a top constraint of value 0
  3. The bottom label needs a bottom constraint of value 0

And that's all!

Here's a sketch to show the constraints:

enter image description here

In case you are using Masonry or SnapKit for your Auto Layout here is how those constraints would be added in code:

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)
}
like image 74
joern Avatar answered Nov 30 '22 19:11

joern