标签:
Autolayout讲解较多的就是xib和storyboard用法,本文主要记录纯代码的Autolayout使用方法:
方法1.苹果原生的方法,这种方法虽然简单但是太过繁杂,可用性很差
//宽度=superView高度 [superView addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeWidth multiplier:1 constant:0]]; //高度=40 [superView addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:0 constant:40]]; //view1底部距离superView底部距离为0 [superView addConstraint:[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
方法2.VFL方法:
//view1距离superview两端距离都为0 [superView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view1]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view1)]]; //view1高度为40,距离底端距离为0 [superView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view1(==40)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view1)]];
注意:
-(void)addConstraint:(NSLayoutConstraint *)constraint;
用来将约束添加到view。在添加时唯一要注意的是添加的目标view要遵循以下规则:
1.对于两个同层级view之间的约束关系,添加到他们的父view上
2对于两个不同层级view之间的约束关系,添加到他们最近的共同父view上
3对于有层次关系的两个view之间的约束关系,添加到层次较高的父view上
方法3.第三方库Masonry
[view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.width.equalTo(superView);
make.height.equalTo(@40);
}];
参考原文档:
http://blog.csdn.net/sxfcct/article/details/8776928
http://www.zhihu.com/question/37095424
masonry下载网址:
https://github.com/SnapKit/Masonry
标签:
原文地址:http://www.cnblogs.com/sunjianfei/p/5650412.html