AutoLayout概念是苹果自iOS6开始引入的概念。
目前为止,实现自动布局技术选型方面也可以使用xib和storyboard。在开发过程中通常登录、注册等变动可能性较小的视图,我会采用xib开发,其他页面通常会采用Masonry布局。xib和手码各有优势,视情况而定。
关于NSLayoutAttributeLeading和NSLayoutAttributeTrailing,前边和后边并不是总是为左边和右边的,有些国家的前边是右边后边是左边所以这样设定是为了国际化考虑。还有视图基准线NSLayoutAttributeBaseline通常是指视图的底部放文字的地方。
使用NSLayoutConstraint之前,我们需要确定一点:为了防止constraint和view本身的autoresizing属性冲突,我们需要设置view的属性:
view.translatesAutoresizingMaskIntoConstraints = NO;
一、UIKit框架提供的自动布局的方法一,详细请看参数介绍:
/** 设置约束 @param view1 指定需要添加约束的视图一 @param attr1 指定视图一需要约束的属性 @param relation 指定视图一和视图二添加约束的关系 @param view2 指定视图一依赖关系的视图二;可为nil @param attr2 指定视图一所依赖的视图二的属性,若view2=nil,该属性设置 NSLayoutAttributeNotAnAttribute @param multiplier 系数 情况一和二为亲测 情况一:设置A视图的高度 = A视图高度 * multiplier + constant;此时才会起作用; 情况二:设置A视图和其他视图的关系或 toItem=nil,multiplier设置不等于0即可,若等于0会crash; @param c 常量 @return 返回生成的约束对象 */ + (instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(nullable id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;
以上函数设置的约束等价于 view1.att1 =(以等号举栗子,relation可> < ≥≤)view2.attr2 * multiplier + c;
简单小需求:随意在控制器中添加一个红色view:
// 设置 redView 的宽 = 100.f * 1.f NSLayoutConstraint *redViewWidthConstraint = [NSLayoutConstraint constraintWithItem:self.redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:100.f]; // 设置 redView 的高 = 100.f * 1.f NSLayoutConstraint *redViewHeightConstraint = [NSLayoutConstraint constraintWithItem:self.redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:100.f]; // 设置 redView 的前面(左边) = self.view.leading + 20.f NSLayoutConstraint *redViewleadingConstraint = [NSLayoutConstraint constraintWithItem:self.redView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.f constant:20.f]; // 设置 redView 的顶部 NSLayoutConstraint *redViewTopConstraint = [NSLayoutConstraint constraintWithItem:self.redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.f constant:30.f]; [self.view addConstraint:redViewWidthConstraint]; [self.view addConstraint:redViewHeightConstraint]; [self.view addConstraint:redViewleadingConstraint]; [self.view addConstraint:redViewTopConstraint];
小注:
1、关于参数 multiplier
✅举个栗子