- (void)viewDidLoad { [super viewDidLoad]; //1.view1 居中显示 UIView *view1 = [[UIView alloc]init]; view1.backgroundColor = [UIColor redColor]; [self.view addSubview:view1]; [view1 mas_makeConstraints:^(MASConstraintMaker *make) { make.center.equalTo(self.view); //居中 make.size.mas_equalTo(CGSizeMake(300, 300)); //设置宽高 //make.size.equalTo(@100); //设置size //make.size.mas_equalTo(@100); }]; //2.view2 在view1的正中间 UIView *view2 = [UIView new]; view2.backgroundColor = [UIColor blackColor]; [view1 addSubview:view2]; [view2 mas_makeConstraints:^(MASConstraintMaker *make) { // make.top.left.bottom.and.right.equalTo(view1).with.insets(UIEdgeInsetsMake(10, 10, 10, 10)); 等价于: // make.top.equalTo(view1).with.offset(10); // make.left.equalTo(view1).with.offset(10); // make.bottom.equalTo(view1).with.offset(-10); // make.right.equalTo(view1).with.offset(-10); // 也等价于: //设置四边缩进20 make.edges.equalTo(view1).with.insets(UIEdgeInsetsMake(20, 20, 20, 20)); // make.size.width.equalTo(@200); // make.size.height.equalTo(@200); // }]; 注意点: /* mas_makeConstraints 只负责新增约束 Autolayout不能同时存在两条针对于同一对象的约束 否则会报错 mas_updateConstraints 针对上面的情况 会更新在block中出现的约束 不会导致出现两个相同约束的情况 mas_remakeConstraints 则会清除之前的所有约束 仅保留最新的约束 [view1 mas_makeConstraints:^(MASConstraintMaker *make) { }]; [view1 mas_remakeConstraints:^(MASConstraintMaker *make) { }]; [view1 mas_updateConstraints:^(MASConstraintMaker *make) { }]; */ //3.view3与view1 在同一列 UIView *view3 = [UIView new]; view3.backgroundColor = [UIColor greenColor]; [self.view addSubview:view3]; [view3 mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(100, 100)); make.centerX.equalTo(view1); //设置水平居中 make.top.equalTo(view1.mas_bottom).with.offset(20); //与上view的垂直间隔 }]; }