Tôi muốn hình ảnh con của tôi là hình chữ nhật 16: 9 ở trên cùng của trình giám sát. Nói cách khác, tôi muốn nó:Mã NSLayoutConstraints để căn giữa chế độ xem và duy trì tỷ lệ khung hình
- được rộng như nó SuperView, nhưng không lớn hơn 400px (UI có thể xoay theo chiều ngang),
- được tập trung theo chiều ngang khi nó hẹp hơn đó là SuperView,
- có phần trên cùng được gắn vào đầu của người giám sát và
- thay đổi chiều cao của nó để duy trì tỷ lệ khung hình 16: 9.
Mã này gần như không nó, ngoại trừ tôi đang gặp một thời gian khó khăn làm hạn chế ngang làm việc và không có trên hoặc dưới chế ...
- (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];
}
Chắc chắn là vậy. Câu trả lời rất hữu ích. Cảm ơn. – danh