我认为您真正想要的如下: 1.Label 的顶部距离其 superView 100,底部距离其 superView 68 2.在 4 英寸显示屏中,其尺寸为 200x400,比例为 0.5 3.在 3.5 英寸显示屏中,其尺寸为 312x624,比例为 0.5
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// create search bar
CGRect frame = CGRectMake(60, 100, 200, 400);
_label = [[UILabel alloc] initWithFrame:frame];
_label.backgroundColor = [UIColor blueColor];
[self.view addSubview:_label];
// layout search bar
_label.translatesAutoresizingMaskIntoConstraints = NO;
// height
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:_label
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationLessThanOrEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:0
constant:400];
// width
[_label addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:_label
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:_label
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0];
[_label addConstraint:constraint];
// vertical
NSDictionary *views = NSDictionaryOfVariableBindings(_label, self.view);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[_label]-68-|"
options:0
metrics:nil
views:views];
[self.view addConstraints:constraints];
// horizontal
constraint = [NSLayoutConstraint constraintWithItem:_label
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0];
[self.view addConstraint:constraint];
}