简介
iOS设备目前有多种屏幕大小。在之前文章里介绍了一些iOS屏幕的尺寸(点击查看)。多样化的屏幕给开发布局带来了一定的困难。约束布局通过描述元素的相对关系来实现自动适配,降低通过代码布局的难度。
方法
第一步要确保story board的Use Autolayout是选中的。
约束布局大致有三种方式:
在story board上在手工布局
操作示例:
- 两个控件设置一样的宽度
选中要操作的两个控件,然后选择菜单 :
- 水平居中
在右下方工具栏也有快捷按钮可以操作:
或者使用鼠标右键操作:
当然也可以用鼠标左键+ctrl键拖动控件。
约束类别:
width 宽度固定
height 高度固定
页边距约束 Leading and Trailing space
Leading space to Superview :左边距
Trailing space to Superview :右边距
Top space to Superview:上边距
Bottom space to Superview:下边距
间距约束
Horizontal spacing:水平距离
Vertical Spacing:垂直距离
等宽等高约束
Equal width constraint
Equal height constraint
方向比例约束 Aspect ratio constraint
通过代码添加约束
原型
[NSLayoutConstraint constraintWithItem:(id)item
attribute:(NSLayoutAttribute)attribute
relatedBy:(NSLayoutRelation)relation
toItem:(id)otherItem
attribute:(NSLayoutAttribute)otherAttribute
multiplier:(CGFloat)multiplier
constant:(CGFloat)constant]
枚举值:
typedefNS_ENUM(NSInteger, NSLayoutRelation) {
NSLayoutRelationLessThanOrEqual = -1, //小于等于
NSLayoutRelationEqual = 0, //等于
NSLayoutRelationGreaterThanOrEqual = 1, //大于等于
};
typedefNS_ENUM(NSInteger, NSLayoutAttribute) {
NSLayoutAttributeLeft = 1, //左侧
NSLayoutAttributeRight, //右侧
NSLayoutAttributeTop, //上方
NSLayoutAttributeBottom, //下方
NSLayoutAttributeLeading, //首部
NSLayoutAttributeTrailing, //尾部
NSLayoutAttributeWidth, //宽度
NSLayoutAttributeHeight, //高度
NSLayoutAttributeCenterX, //X轴中心
NSLayoutAttributeCenterY, //Y轴中心
NSLayoutAttributeBaseline, //文本底标线
NSLayoutAttributeNotAnAttribute = 0 //没有属性
};
示例:
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:note
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:10]];
可视化的VFL语言添加约束
这个暂时我没有使用,以后再看用法。