IOS 代码添加约束

1.如果是通过代码添加Autolayout, 那么必须在添加约束之前禁用Autoresizing
2.禁用Autoresizing时, 必须是给谁添加就禁用谁的, 也就是说如果禁用了父控件无效
3.添加约束之前, 必须保证被约束的控件已经添加到父控件中了
self.view.translatesAutoresizingMaskIntoConstraints = NO;

Item == 第一个控件
attribute == 第一个控件的什么属性
relatedBy == 等于/小于等于/大于等于
toItem == 第二个控件
attribute == 第二个控件的什么属性
multiplier == 乘以多少
constant == 加上多少

NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
[self.view addConstraint:topCos];

Demo

UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];

redView.translatesAutoresizingMaskIntoConstraints = NO;

 // 2.1顶部约束
NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
[self.view addConstraint:topCos];

// 2.1左边约束
NSLayoutConstraint *leftCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
[self.view addConstraint:leftCos];

// 2.1底部约束
NSLayoutConstraint *bottomCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-20];
[self.view addConstraint:bottomCos];

// 2.1右边约束
NSLayoutConstraint *rightCos = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20];
[self.view addConstraint:rightCos];

//    写在这里不行, 必须在设置约束之前添加
//    [self.view addSubview:redView];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容