OC-Masonry, Swift-SnapKit两种自动布局是开发中常用到的自动布局方式,也是每个开发者必会的一种技能就不再介绍了。在这里说一说原生的自动布局方法。
原生一:_titleLabel被约束试图,AdaH(26)偏移量,self参照试图,代码在UITableViewHeaderFooterView中写的
[NSLayoutConstraint constraintWithItem:<#(nonnull id)#> attribute:<#(NSLayoutAttribute)#> relatedBy:<#(NSLayoutRelation)#> toItem:<#(nullable id)#> attribute:<#(NSLayoutAttribute)#> multiplier:<#(CGFloat)#> constant:<#(CGFloat)#>] 类方法
_titleLabel.translatesAutoresizingMaskIntoConstraints = NO;// 关闭系统自动布局方式
NSLayoutConstraint *titleTop = [NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:AdaH(26)]; NSLayoutConstraint*titleLeft = [NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:AdaH(16)];
[self.contentView addConstraints:@[titleTop,titleLeft]];// 错误reason: 'Impossible to set up layout with view hierarchy unprepared for constraint.'
[self addConstraints:@[titleTop,titleLeft]];// 正确
1.参数说明:
第一个参数_titleLabel:指定约束的视图view1
第二个参数NSLayoutAttributeTop:指定view1的属性attr1(上、下、左、右、x轴y轴)
第三个参数NSLayoutRelationEqual:指定左右两边的视图的关系relation(下面介绍)
第四个参数self:指定约束参考的视图view2
第五个参数NSLayoutAttributeLeft:同参数2
第六个参数1.0:相乘的乘数multiplier
第七个参数constant:指定一个与view2属性相加的浮点数constant
依据的公式是:view1.attr1 = view2.attr2*multiplier +constant
NSLayoutRelationEqual官方参数
NSLayoutRelationLessThanOrEqual 视图关系小于或等于
NSLayoutRelationEqual 视图关系等于
NSLayoutRelationGreaterThanOrEqual 视图关系大于或等于