APP最低支持iOS9.0,部分布局開始使用UIStackView。但是其有些許局限性,比如不能設(shè)置背景顏色、在iOS11之后才支持對間距的不同調(diào)整。鑒于此,對其進行了一些嘗試。
一、對背景顏色的支持。
UIStackView是UIView 的子類,但是官方說在層級中是不對其渲染。然后抱著嘗試 的心態(tài),在UIStackView的子類中重寫了 + (Class)layerClass,然后按UI View 的方法設(shè)置背景顏色、圓角等,竟然生效了。奈斯!
+ (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之后的間距做出調(diào)整,著實有用。遂也重寫該方法。customSpacingView是一個保存arrangedSubview的集合,簡單的保證唯一性,待之后布局調(diào)整時使用。本文章只是一些嘗試,暫為保存要設(shè)定的spacing。然后輸出所有的constraints,發(fā)現(xiàn)一個可疑對象constraint的identifier值為UISV-spacing,修改其值(統(tǒng)一值為5,該處固定調(diào)到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中有很多細節(jié)并沒有完全考慮,使用中或許需要優(yōu)化。哪位大佬有好的想法,或者有好的指導問題,歡迎留言。
謝謝。