iOS App开发中的UIStackView堆叠视图使用教程

2020-01-15 16:00:24丽君

        float height = arc4random()%90+10;
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo([NSNumber numberWithFloat:height]);
        }];
        [array addObject:view];
    }
    stackView = [[UIStackView alloc]initWithArrangedSubviews:array];
    [self.view addSubview:stackView];
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.leading.equalTo(self.view.mas_leading).offset(20);
        make.trailing.equalTo(self.view.mas_trailing).offset(-20);
        make.size.height.equalTo(@100);
    }];
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.distribution = UIStackViewDistributionFillEqually;
    stackView.alignment = UIStackViewAlignmentCenter;
效果如下:

iOS,UIStackView,堆叠视图,视图

iOS,UIStackView,堆叠视图,视图

这样,参差不齐的控件布局我们也可以轻松完成。
3.排列方式
@property(nonatomic) UIStackViewDistribution distribution;
排列方式的枚举如下:
typedef NS_ENUM(NSInteger, UIStackViewDistribution) {
    //充满,当只有一个控件时可以使用
    UIStackViewDistributionFill = 0,
    //平分充满,每个控件占据相同尺寸排列充满
    UIStackViewDistributionFillEqually,
    //会优先按照约束的尺寸进行排列,如果没有充满,会拉伸最后一个排列的控件充满
    UIStackViewDistributionFillProportionally,
    //等间距排列
    UIStackViewDistributionEqualSpacing,
    //中心距离相等
    UIStackViewDistributionEqualCentering,
} NS_ENUM_AVAILABLE_IOS(9_0);

注意,除了我们选择fill属性时不需约束控件视图的尺寸,其他都需要进行约束,例如如果我们选择等间距,我把改成如下代码:
     [view mas_makeConstraints:^(MASConstraintMaker *make) {