IOS 代码添加约束
2018-05-12 本文已影响0人
路小白同学
项目中页面代码布局使用的一般都是Masonry,修改以前的项目是发现有的页面是用OC原生的NSLayoutConstraint进行布局。做个记录,以后忘了可以瞄一眼~
1.如果是通过代码添加Autolayout, 那么必须在添加约束之前禁用Autoresizing
2.禁用Autoresizing时, 必须是给谁添加就禁用谁的, 也就是说如果禁用了父控件无效
3.添加约束之前, 必须保证被约束的控件已经添加到父控件中了
self.view.translatesAutoresizingMaskIntoConstraints = NO;
Item == 第一个控件
attribute == 第一个控件的什么属性
relatedBy == 等于/小于等于/大于等于
toItem == 第二个控件
attribute == 第二个控件的什么属性
multiplier == 乘以多少
constant == 加上多少
NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:messageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
[self.view addConstraint:topCos];
给view添加宽度
NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:messageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:100];
[self.view addConstraint:topCos];
如此就可了。