我希望我的子视图是一个 16:9 的矩形,位于其父视图的顶部。换句话说,我希望它:
- 与其superview一样宽,但不超过400px(UI可以旋转到横向),
- 当它比它的超级视图窄时水平居中,
- 将其顶部固定到其超级视图的顶部,并且
- 更改其高度以保持 16:9 的纵横比。
这段代码几乎可以做到,除了我很难使水平约束起作用并且没有过度或不足约束......
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIView *contentView = [[UIView alloc] init];
contentView.backgroundColor = [UIColor redColor];
[self.view addSubview:contentView];
contentView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *views = NSDictionaryOfVariableBindings(contentView);
NSMutableArray *constraints = [NSMutableArray array];
// this layout string is more like 'wishful coding'. I don't see why it wouldn't work
// but clearly this one is the problem
[constraints addObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-(>=0)-[contentView(<=400)-(>=0)-]"
options:0 metrics:0 views:views]];
// this centering constraint below almost does the job, but doesn't give me a way
// to specify width, changing the one above to just @"H:[contentView(<=400)]"
// doesn't work either
[constraints addObject:
[NSLayoutConstraint constraintWithItem:contentView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.f constant:0.f]];
// 9:16 works fine, I think
[constraints addObject:
[NSLayoutConstraint constraintWithItem:contentView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:contentView attribute:NSLayoutAttributeWidth
multiplier:9.0/16.0 constant:0.0]];
// pin the tops works fine, I think
[constraints addObjectsFromArray:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[contentView]"
options:0 metrics:0 views:views]];
[self.view addConstraints:constraints];
}