iOS AutoLayout

之前一直使用Masonry布局,对官方的自动布局不太了解。但是有些页面逻辑、页面复杂时,布局效果往往不尽如人意,所以查阅资料,熟悉一下。

UIView *view = [UIView new];
view.backgroundColor = [UIColor redColor];
view.translatesAutoresizingMaskIntoConstraints = NO; // 标识自动布局

[self.view addSubview:view];

NSLayoutConstraint *constraint1 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:20];
NSLayoutConstraint *constraint2 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:20];
NSLayoutConstraint *constraint3 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:0 constant:20];
NSLayoutConstraint *constraint4 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:50];

[self.view addConstraint:constraint1]; // 参照等约束加在父视图上
[self.view addConstraint:constraint2];
[view addConstraint:constraint3]; // 自身尺寸的约束加在本身上
[view addConstraint:constraint4];

你可能感兴趣的:(iOS AutoLayout)