@interface MainViewController ()
@property(nonatomic, strong) UIView *firstView;
@property(nonatomic, strong) UIView *secondView;
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self firstView];
[self secondView];
[self layout];
}
- (UIView *)firstView
{
if (!_firstView) {
self.firstView = [[UIView alloc] init];
self.firstView.backgroundColor = [UIColor redColor];
self.firstView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:_firstView];
}
return _firstView;
}
- (UIView *)secondView
{
if (!_secondView) {
self.secondView = [[UIView alloc] init];
self.secondView.backgroundColor = [UIColor yellowColor];
self.secondView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:_secondView];
}
return _secondView;
}
- (void)layout
{
//NSDictionaryOfVariableBindings 宏 其实 NSDictionaryOfVariableBindings(v1, v2, v3) 等效于 [NSDictionary dictionaryWithObjectsAndKeys:v1, @"v1", v2, @"v2", v3, @"v3", nil];
NSDictionary *views = NSDictionaryOfVariableBindings(_firstView, _secondView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-30.0-[_firstView]-30.0-|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=200)-[_firstView(50)]" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[_secondView(==_firstView)]" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_secondView(==_firstView)]" options:0 metrics:nil views:views]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_secondView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_firstView attribute:NSLayoutAttributeRight multiplier:1 constant:10]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_secondView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_firstView attribute:NSLayoutAttributeLeading multiplier:1 constant:0]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end