iOS记录

UIStackView

2020-07-18  本文已影响0人  bianruifeng

UIStackView共四个属性:
1、axis 排列
2、distribution 填充
3、alignment 对齐
4、spacing 间距

typedef NS_ENUM(NSInteger, UILayoutConstraintAxis) {
    UILayoutConstraintAxisHorizontal = 0 ,    //水平方向布局 (默认)
    UILayoutConstraintAxisVertical = 1         //垂直方向布局
};

演示如图:


image.png

arrangedSubviews数组
UIStackView使用arrangedSubviews数组来管理子视图。需要注意的是这个数组是一个readonly的属性,我们需要调用方法对arrangedSubviews数组进行操作。
初始化数组:
- (instancetype)initWithArrangedSubviews:(NSArray<__kindof UIView *> *)views;
添加子视图:
- (void)addArrangedSubview:(UIView *)view;
移除子视图:
- (void)removeArrangedSubview:(UIView *)view;
根据下标插入视图:
- (void)insertArrangedSubview:(UIView *)view atIndex:(NSUInteger)stackIndex;

编码添加约束:
UIStackView 的布局使用frame是没有任何效果的。
可以与其他约束框架Masonry混合使用,仅能约束宽高,不能约束边界。

- (void) setup {

    //View 1
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor blueColor];
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 100));
    }];
//    [view1.heightAnchor constraintEqualToConstant:100].active = true;
//    [view1.widthAnchor constraintEqualToConstant:120].active = true;


    //View 2
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor greenColor];
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(300, 20));
    }];
//    [view2.heightAnchor constraintEqualToConstant:100].active = true;
//    [view2.widthAnchor constraintEqualToConstant:70].active = true;

    //View 3
    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor magentaColor];
    [view3.heightAnchor constraintEqualToConstant:100].active = true;
    [view3.widthAnchor constraintEqualToConstant:180].active = true;

    //Stack View
    UIStackView *stackView = [[UIStackView alloc] init];

    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.spacing = 30;

    [stackView addArrangedSubview:view1];
    [stackView addArrangedSubview:view2];
    [stackView addArrangedSubview:view3];

    stackView.translatesAutoresizingMaskIntoConstraints = false;
    [self.view addSubview:stackView];


    //Layout for Stack View
    [stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
    [stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;
}

效果如图:


6.png
上一篇下一篇

猜你喜欢

热点阅读