UIScrollview+Masonry
作为Masonry的脑残粉,在做工程的时候却被UIScrollview+Masonry给难住了。因为我无论怎样设置contentsize都不管用,UIScrollView会尽可能地边长变宽来适应内容。Google了一下,发现已经有大神总结了UIScrollview+Masonry的使用方法。摘抄+部分翻译如下:
1. 第一篇博客
原文:http://www.pixeldock.com/blog/uiscrollview-and-auto-layout/
纵向滑动
- The topmost subview must have a top constraint with the UIScrollView
- All other subviews must have a top constraint with the bottom constraint of the subview above them
- The bottommost subview must have a bottom constraint with the UIScrollView
总结一下,要想让UIScrollView纵向可以滑动,就要把最上面的subView的top和最下面subView的bottom分别设置好与UIScrollView的constraint,中间的subView的top和其上面subView的bottom有constraint就好啦!
横向固定
Do not rely on left and right constraints to define the width of a subview.
不要试图用一个subView的left和right来限定一个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.
举个例子,如果你有一个UILabel,里面有很多text,即使你设置了numberOfLines=0
它也不会分成多行显示。因为UIScrollView会给它提供足够的空间来水平滑动显示完全。所以如果你只设了left和right的constraint,UIScrollView就会为了适应UILabel的text的长度而变得横向可滑动,label也只会变得很宽,只会显示一行。
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.
因此,要设置left和width的constraint。只要把width设置为你想要的UIScrollView的width,label就不会变得很宽,而是会变为多行显示!
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.
如果你遵循了上述步骤,就不必设置UIScrollView的 contentSize了。 Auto Layout已经帮你完成自动布局了。
To make it more clear, here is an image with the constraints that you have to set:
为了表达更清晰一些,这里有个设置constraint时的示范图:
2. LJC的博客
原文:http://adad184.com/2015/12/01/scrollview-under-autolayout/
LJC的方法是用一个给所有的subView加一个container,然后设置container的constraint:
make.edges.equalTo(scrollView);
make.width.equalTo(scrollView);
总之:
如果我们需要竖向的滑动 就把width设为和scrollview相同
如果需要横向的滑动 就把height设为和scrollview相同
设置原因和demo都有,可以去大神博客看。
网友评论