先看结果:
再看代码:
- (id)init {
self = [super init];
if (!self) return nil;
UIView *lastView = self;
for (int i = ; i < ; i++) {
UIView *view = UIView.new;
view.backgroundColor = [self randomColor];
view.layer.borderColor = UIColor.blackColor.CGColor;
view.layer.borderWidth = ;
[self addSubview:view];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(lastView).insets(UIEdgeInsetsMake(, , , ));
}];
lastView = view;
}
return self;
}
- (UIColor *)randomColor {
CGFloat hue = ( arc4random() % / ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % / ) + ; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % / ) + ; // 0.5 to 1.0, away from black
return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:];
}
至于循环10次来添加约束这个逻辑很容易理解,我关注的是edges这个复合数据结构。可以想象一下,我就布局一个简单的视图在父视图上,要确定其上下左右,可以使用基本布局中的方式:
make.top.equalTo(superview.top).offset();
make.left.equalTo(superview.left).offset();
make.bottom.equalTo(superview.bottom).offset(-);
make.right.equalTo(superview.right).offset(-);
也可以使用常量:
make.top.equalTo(@10);
make.left.equalTo(@10);
make.bottom.equalTo(@-);
make.right.equalTo(@-);
也可以使用edges:
你想用哪个?