参考文章
https://www.weheartswift.com/auto-layout-101/
1. 各个选项的含义
Leading space to container: view左边界到容器左边界的距离
Trailing Space to Container: view右边界到容器右边界的距离
同理 Top space to container, 和 Bottom Space to container
Aspect Ratio 保持纵横比,如果屏幕增高,那么设置了纵横比的View宽度也会增高。
如果要保持View的高度也增高,那么再对自己本身设置纵横比即可。
Center Horizontally in Container ,水平居中
Center Vertically in Container , 竖直居中
2、同理设置 space to container margin是一样的,只是ios 有默认的边界宽度
The default margin on iOS is {top: 8, left: 16, bottom: 8, right: 16}
on iPhone and {top: 8, left: 20, bottom: 8, right: 20}
on iPad. To change this you need to set the layoutMargins
property in code.
container.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 10, right: 20)
接下来我们来实现一个第三方分享的页面自动布局,界面大致是这样
新建sigleViewApplication,在storyboard 中实现如上图的布局,将模拟器调整为最小的屏幕
接下来,我们要实现在所有屏幕中都是同一个样式。
1.先保证contentView显示在屏幕的底部
右键拖动contentView到superView,为其设置三个属性leading space to container, equal widths, bottom space to container margin
contentView 鼠标右键拖动到自己,为其设置hight 保持宽度固定。
开始预览自动布局效果:
点击
再选择
选择预览
在预览窗口添加不同尺寸的模拟器,iphone7 ,iPhone 7 plus, iPhone SE
可以看到contentView已经自动布局到了屏幕底部
我们来分析一下autolayout 的属性
contentView.leading = leading, 即为 contentView的左边位置 = superview的左边界
contentView.width = width , 即为 cotentView的宽度 = superVIew 的宽度
...
不过在iPhone 7 以上的屏幕,分享按钮都没有自动布局到相应的位置,接下来开始添加自动布局属性.
WeChat Button
接下来给weChat 添加自动布局,鼠标左键weChat拖动到contentView,为其添加 top space to container, leading space to container.
weChat 鼠标左键拖动到自己,旋转hight 和width 固定宽高。
Moment Button,
保持其居中位置,右键拖到contentView,设置center Horizontally in container,水平居中, top space to container,保持顶部距离,
鼠标拖动到自己,旋转hight 和width 保持宽高。
同理设置 QQ Button,
右键拖动到superView,设置trailing space to container, top space to container, 拖动到自己,固定宽高。
接下来就是label 的设置,以 "QQ" label 为例。
左键拖动到 QQ Button, 为其设置center Horizontally,vertical space, 保持 y方向间距,保持与button 水平居中对齐。
左键拖动到自己,限制宽高。
将其于label 按照同样的方式进行设置,也许有些微的变动,最后自动布局也就设置好了
写这个真心浪费时间,很佩服写英文博课的人,写的那么详细。
源代码地址点击打开链接