UIScrollview+Masonry

UIScrollview+Masonry


作为Masonry的脑残粉,在做工程的时候却被UIScrollview+Masonry给难住了。因为我无论怎样设置contentsize都不管用,UIScrollView会尽可能地边长变宽来适应内容。Google了一下,发现已经有大神总结了UIScrollview+Masonry的使用方法。摘抄+部分翻译如下:

1. 第一篇博客

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

纵向滑动

  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

总结一下,要想让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的leftright来限定一个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会给它提供足够的空间来水平滑动显示完全。所以如果你只设了leftright的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.
因此,要设置leftwidth的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时的示范图:

UIScrollView

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都有,可以去大神博客看。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Masonry是一个非常好用的布局工具,如果不知道如何在Xamarin.iOS中使用Masonry,可以参考我写的...
    临岁之寒阅读 1,005评论 0 3
  • 简介 SDWebImage 是目前使用最广泛的第三方图片处理库,它不仅能够异步加载网络图片,还提供了一套图片缓存管...
    Leon_520阅读 1,147评论 0 10
  • 早晨朋友探讨如何将新业务扭亏为盈,再次关联到做好预算和计划的重要性 魔旅老王就很聪明,在意识到线下门店的进账只能养...
    宸世间阅读 262评论 0 1
  • 适当距离 产生惊喜 今天他好像对我特别好呀,不知道是这两天我不在伙食太差突然一下伙食好了感动的,还是太想我了,总之...
    fangyuanjili阅读 204评论 0 0
  • 现代学校源自于十八世纪中叶工业革命之后的社会发展需求,教育界对于教学与学习采「容器观」,也就是认为知识是由外在灌输...
    王者之声阅读 1,947评论 3 4