项目中可能会遇到的一种排版方式,见图
废话少说,直接上代码
UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 300, 300)];
bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.05];
[self.view addSubview:bgView];
for (int i = 1; i<=9; i++) {
CGFloat width = 60;
CGFloat height = 60;
CGFloat spaceW = 10.0;
UIView *view = [UIView new];
view.frame = CGRectMake(0, 0, width, height);
view.backgroundColor = [self randomColor];
[bgView addSubview:view];
// X = (当前下标-1)%每行显示数量*宽度 + (当前下标-1)%每行显示数量*间隙 + 间隙
CGFloat x = (i-1)%4*width + (i-1)%4*spaceW + spaceW;
// Y = (当前下标-1)/每行显示数量*高度 + (当前下标-1)/每行显示数量*间隙 + 间隙
CGFloat y = (i-1)/4*height + (i-1)/4*spaceW + spaceW;
view.frame = CGRectMake(x, y, width, height);
}
- (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];
}