纯代码书写严谨,xib布局拖拽简便.UIScrollView 的xib布局网上有很多案例,今天给大家梳理一下;
在Xcode11中对UIScrollView在Xib中的布局,苹果引入了Content Layout guide和Frame Layout Guide。我们拖动一个UIScrollView到Xib中,默认就会有Content Layout guide和Frame Layout Guide两个选项嵌入。如下图:

这时我们可以选择两种方式来进行布局:
(一)将右边检查器中Content Layout Guides的勾勾去掉,这样Content Layout guide和Frame Layout Guide在UIScrollView中就会自动消失,这时候布局就跟以前的Xcode版本一样,
1.将右边检查器中Content Layout Guides的勾勾去掉

2.在ScrollView中拖拽进一个view ,当作容器视图contentView.并给contentView添加约束,(此时是给contentView添加约束,ScrollView先不添加任何约束),contentView的高度可以先给定一个默认值,之后可以将ContentView高度约束作为属性拖出来,用代码来修改约束高度
tips:
垂直滑动布局:contentView上下左右添加约束,水平居中,本文演示的是垂直滑动布局(反之,水平滑动布局:contentView上下左右添加约束,垂直居中);

3.这时有报错不用担心,接下来设置好UIScrollView的约束(即:UIScrollView上下左右添加约束)报错就会消失,这时布局就完成了,contentView作为UIScrollView的容器视图,就可以垂直拖动了,如果不能拖动那就是有问题.接下来就可以随意给容器中添加子视图了.

(二)保留Content Layout guide和Frame Layout Guide,分别对它们进行设置,完成UIScrollView的内容布局,
1.保留Content Layout guide和Frame Layout Guide,即将右边检查器中Content Layout Guides的勾勾选中.设置ScrollView相对于父视图的约束,即上下左右设置约束.最后拖一个view到UIScrollView中作为容器视图contentView,

2.Autolayout将使用这个contentView的宽高来计算UIScrollView的滚动范围,分别设置contentView相对于Content Layout guide的约束为0,具体步骤为:左键选中contentView,右键拖动它到Content Layout guide上,按住shift键,将上下左右都给选中,如果xcode默认了当前的相对数据,在右边四个约束将它手动改为0,操作如下图


3.上面的步骤设置之后,我们会发现红线仍然存在,这是因为AutoLayout仍然不知道内容的滚动范围是多大,我们接下来设置滚动范围,具体步骤为,左键选中ContentView,右键拖动到Frame Layout Guide,如果是垂直布局就选中Equal Widths,反之选择Equal Height. 最后在设置ContentView的高度即可.


如果可以上下拖动ContentView,那就说明布局成功.可以在ContentView中添加其他子控件了.

以上就是我给大家总结的scrollView的xib布局,如有疑问欢迎留言一起探讨.
tips:上面还有一个红色警告,正解是选中控制器,右边面板的Builds for 选择iOS11.0 and Later,如下图红框
广为流传的错解是不勾选Use Safe Area Layout Guides,如下图灰框,会导致用不了iOS的这个新功能了


网友评论