UIStackView 学习笔记

参考
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;
}
Simulator Screen Shot - iPhone 8 - 2022-11-19 at 16.49.48.png

你可能感兴趣的:(UIStackView 学习笔记)