AutoLayout自动适配非常关键,因为很常用。
让我们来看看关于按钮的自动适配:
//这里不需要设置大小,反正,反正是自动适配
modelButton = [[UIButton alloc] init];
modelButton.center = self.view.center;
modelButton.layer.cornerRadius = 8;
modelButton.backgroundColor = [UIColor brownColor];
[modelButton setTitle:@"模态" forState:UIControlStateNormal];
[modelButton addTarget:self action:@selector(modelAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:modelButton];
//小伙伴,这句话可不能少,取消button的自动适配
modelButton.translatesAutoresizingMaskIntoConstraints = NO;
NSString *hVFL = @"H:|-topSpace-[button]-bottomSpace-|";
NSString *vVFL = @"V:|-leftSpace-[button]-rightSpace-|";
NSDictionary *metrics = @{@"topSpace":@100,@"bottomSpace":@50,@"leftSpace":@80,@"rightSpace":@90};
NSDictionary *views =@{@"button":modelButton};
NSArray *hConstraint = [NSLayoutConstraint constraintsWithVisualFormat:hVFL
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:metrics
views:views];
NSArray *vConstraint = [NSLayoutConstraint constraintsWithVisualFormat:vVFL
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:metrics
views:views];
NSMutableArray *constraintArray = [[NSMutableArray alloc] init];
//这样不行的原因是因为:addObject只能存储对象,而不能存储对象数组 所以要用addObjectsFromArray
// [constraintArray addObject:hConstraint];
// [constraintArray addObject:vConstraint];
[constraintArray addObjectsFromArray:hConstraint];
[constraintArray addObjectsFromArray:vConstraint];
[self.view addConstraints:constraintArray];
// [self.view addConstraints:hConstraint];
// [self.view addConstraints:vConstraint];


网友评论