参考
https://www.jianshu.com/p/e53d8ab96c09
代码
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *redButton = [UIButton buttonWithType:UIButtonTypeCustom];
[redButton setTitle:@"" forState:UIControlStateNormal];
redButton.backgroundColor = [UIColor redColor];
UIButton *greenButton = [UIButton buttonWithType:UIButtonTypeCustom];
[greenButton setTitle:@"" forState:UIControlStateNormal];
greenButton.backgroundColor = [UIColor greenColor];
UIButton *blueButton = [UIButton buttonWithType:UIButtonTypeCustom];
[blueButton setTitle:@"" forState:UIControlStateNormal];
blueButton.backgroundColor = [UIColor blueColor];
UIStackView *stackView = [[UIStackView alloc]initWithArrangedSubviews:@[redButton,greenButton,blueButton]];
stackView.backgroundColor = [UIColor yellowColor];
stackView.alignment = UIStackViewAlignmentCenter;
stackView.axis = UILayoutConstraintAxisHorizontal;
stackView.distribution = UIStackViewDistributionFill;
stackView.spacing = 4;
[self.view addSubview:stackView];
stackView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addConstraints:@[
[stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],
[stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
]];
redButton.translatesAutoresizingMaskIntoConstraints = NO;
[stackView addConstraints:@[
[redButton.heightAnchor constraintEqualToConstant:13],
[redButton.widthAnchor constraintEqualToConstant:30],
]];
blueButton.translatesAutoresizingMaskIntoConstraints = NO;
[stackView addConstraints:@[
[blueButton.heightAnchor constraintEqualToConstant:13],
[blueButton.widthAnchor constraintEqualToConstant:10],
]];
greenButton.translatesAutoresizingMaskIntoConstraints = NO;
[stackView addConstraints:@[
[greenButton.heightAnchor constraintEqualToConstant:13],
[greenButton.widthAnchor constraintEqualToConstant:20],
]];
greenButton.hidden = YES;
}