mansory使用与UIScrollView

http://www.pixeldock.com/blog/uiscrollview-and-auto-layout/

 

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)
}

转载于:https://my.oschina.net/u/2474234/blog/847216

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值