IOS 代码添加约束

项目中页面代码布局使用的一般都是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];

如此就可了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容