iOS8以后,UIView多了一个新的属性:
@property (nonatomic) UIEdgeInsets layoutMargins NS_AVAILABLE_IOS(8_0);
本例就是对该属性的使用。
效果图:
代码:
- (instancetype)init {
self = [super init];
if (!self) return nil;
UIView *lastView = self;
for (int i = 0; i < 10; i++) {
UIView *view = UIView.new;
view.backgroundColor = [self randomColor];
view.layer.borderColor = UIColor.blackColor.CGColor;
view.layer.borderWidth = 2;
view.layoutMargins = UIEdgeInsetsMake(5, 10, 15, 20);
[self addSubview:view];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(lastView.topMargin);
make.bottom.equalTo(lastView.bottomMargin);
make.left.equalTo(lastView.leftMargin);
make.right.equalTo(lastView.rightMargin);
}];
lastView = view;
}
return self;
}
- (UIColor *)randomColor {
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
个人理解:layoutMargins属性就是用于布局的视图之间的一个参照数据。该属性与Masonry结合,简化了自动布局的代码和语义。