1.设置所约束控件的 translatesAutoresizingMaskIntoConstraints 属性
/*
UIView *blueView = [[UIView alloc]init];
blueView.backgroundColor = [UIColor blueColor];
[self.view addSubview:blueView];
blueView.translatesAutoresizingMaskIntoConstraints = NO;
*/
2.添加对应的约束,如”上,下,左,右“各边距
方法 一 : constraintWithItem:(nonnull id) attribute:(NSLayoutAttribute) relatedBy:(NSLayoutRelation) toItem:(nullable id) attribute:(NSLayoutAttribute) multiplier:(CGFloat) constant:(CGFloat)
参数:constraintWithItem:(nonnull id) ----所约束的控件对象
attribute:(NSLayoutAttribute) -----所约束的位置类型 (枚举)
relatedBy:(NSLayoutRelation)------与相对控件的关系(枚举)
toItem:(nullable id) ------ 约束所相对的控件对象
attribute:(NSLayoutAttribute)-------约束相对的位置类型(枚举)
multiplier:(CGFloat) ------ 比例因子 ((约束控件 + constant值 ) X 比例因子)
constant:(CGFloat) ------ 间隔 (左、上正值 右下负值)
/*
//设置左
NSLayoutConstraint *layoutL = [NSLayoutConstraint constraintWithItem:blueView attribute:(NSLayoutAttributeLeft) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeLeft) multiplier:1 constant:10];
[self.view addConstraint:layoutL];
//设置右
NSLayoutConstraint *layoutR = [NSLayoutConstraint constraintWithItem:blueView attribute:(NSLayoutAttributeRight) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeRight) multiplier:1 constant:-10];
[self.view addConstraint:layoutR];
//设置上
NSLayoutConstraint *layoutT = [NSLayoutConstraint constraintWithItem:blueView attribute:(NSLayoutAttributeTop) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeTop) multiplier:1 constant:40];
[self.view addConstraint:layoutT];
//设置下
NSLayoutConstraint *layoutB = [NSLayoutConstraint constraintWithItem:blueView attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeBottom) multiplier:1 constant:-400];
[self.view addConstraint:layoutB];
*/
方法 二 :constraintsWithVisualFormat:(nonnull NSString *) options:(NSLayoutFormatOptions) metrics:(nullable NSDictionary*) views:(nonnull NSDictionary*)
参数:VisualFormat:(nonnull NSString *)----使用了VFL语法 (可参考相关语法)
options:(NSLayoutFormatOptions)----枚举可选默认为0
metrics:(nullable NSDictionary*)---一般为nil
views:(nonnull NSDictionary*) ------ 就是上面所加入到NSDictionary中的绑定的View
约束添加规则:
1)对于两个同层级view之间的约束关系,添加到它们的父view上
2)对于两个不同层级view之间的约束关系,添加到他们最近的共同父view上
3)对于有层次关系的两个view之间的约束关系,添加到层次较高的父view上
/*
NSArray *arry = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[blueView]-20-|" options:0 metrics:nil views:@{@"blueView":blueView}];
[self.view addConstraints:arry];
NSArray *arry1 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[blueView]-20-|" options:0 metrics:nil views:@{@"blueView":blueView}];
[self.view addConstraints:arry1];
*/