美文网首页iOS UI相关
UIStackView背景色和自定义间距

UIStackView背景色和自定义间距

作者: 泰好笑勒 | 来源:发表于2019-12-03 15:24 被阅读0次

    APP最低支持iOS9.0,部分布局开始使用UIStackView。但是其有些许局限性,比如不能设置背景颜色、在iOS11之后才支持对间距的不同调整。鉴于此,对其进行了一些尝试。
    一、对背景颜色的支持。
    UIStackView是UIView 的子类,但是官方说在层级中是不对其渲染。然后抱着尝试 的心态,在UIStackView的子类中重写了 + (Class)layerClass,然后按UI View 的方法设置背景颜色、圆角等,竟然生效了。奈斯!

    + (SDStackView *)horizontalFillEquallyWithSpacing:(CGFloat)spacing {
        SDStackView *sv = [[SDStackView alloc] init];
        sv.distribution = UIStackViewDistributionFillEqually;
        sv.axis = UILayoutConstraintAxisHorizontal;
        sv.spacing = spacing;
        sv.alignment = UIStackViewAlignmentCenter;
        return sv;
    }
    
    + (Class)layerClass {
        return [CALayer class];
    }
    
    - (void)setBackgroundColor:(UIColor *)backgroundColor {
        self.layer.backgroundColor = backgroundColor.CGColor;
    }
    

    二、对自定义间距的尝试。
    在iOS11中新增了- (void)setCustomSpacing:(CGFloat)spacing afterView:(UIView *)arrangedSubview,可以对该subview之后的间距做出调整,着实有用。遂也重写该方法。customSpacingView是一个保存arrangedSubview的集合,简单的保证唯一性,待之后布局调整时使用。本文章只是一些尝试,暂为保存要设定的spacing。然后输出所有的constraints,发现一个可疑对象constraint的identifier值为UISV-spacing,修改其值(统一值为5,该处固定调到15),又生效了。太奈斯拉。

    // @property (nonatomic, strong) NSMutableSet *customSpacingView;
    - (void)setCustomSpacing:(CGFloat)spacing afterView:(UIView *)arrangedSubview {
        if (@available(iOS 11.0, *)) {
            [super setCustomSpacing:spacing afterView:arrangedSubview];
        } else {
            [self.customSpacingView addObject:arrangedSubview];
        }
    }
    
    - (void)updateConstraints {
        [super updateConstraints];
        // NSLog(@">>>%@",self.constraints);
        if (_customSpacingView.count == 0) {
              return;
        }
        __weak typeof(self)wkself = self;
        [self.constraints enumerateObjectsUsingBlock:^(__kindof NSLayoutConstraint * _Nonnull constraint, NSUInteger idx, BOOL * _Nonnull a_stop) {
              if ([constraint.identifier isEqualToString:@"UISV-spacing"]) {
                  [wkself.customSpacingView enumerateObjectsUsingBlock:^(UIView *v, BOOL * _Nonnull b_stop) {
                      if ([v isEqual:constraint.secondItem]) {
                          constraint.constant = 15;
                          *b_stop = YES;
                          *a_stop = YES;
                        }
                    }];
              }
        }];
    }
    

    本篇文章只是对UIStackView一些想法,具体用法或其它属性可以参考官方文档。demo中有很多细节并没有完全考虑,使用中或许需要优化。哪位大佬有好的想法,或者有好的指导问题,欢迎留言。
    谢谢。

    相关文章

      网友评论

        本文标题:UIStackView背景色和自定义间距

        本文链接:https://www.haomeiwen.com/subject/ymbcgctx.html