今天项目有用到九宫格方式排列,就记录一下。
代码如下:
CGFloat gridWidth = 80;//格子的宽度
CGFloat gridHeight = 30;//格子的高度
NSInteger rowNumber = 3;//每行几个
//间距x,y
CGFloat marginX = ([UIScreen mainScreen].bounds.size.width - gridWidth * rowNumber) / (rowNumber + 1);
CGFloat marginY = 20;
for ( int i = 0; i < 12 ; i++) {
UIView *subv = [[UIView alloc] init];
[self.view addSubview:subv];
subv.backgroundColor = [UIColor colorWithHue:( arc4random() % 256 / 256.0 )
saturation:( arc4random() % 128 / 256.0 ) + 0.5
brightness:( arc4random() % 128 / 256.0 ) + 0.5
alpha:1];
[subv mas_makeConstraints:^(MASConstraintMaker *make){
make.left.mas_equalTo(marginX + i % rowNumber * (gridWidth + marginX));
make.top.mas_equalTo(marginY + i / rowNumber * (gridHeight + marginY));
make.width.mas_equalTo(gridWidth);
make.height.mas_equalTo(gridHeight);
}];
}
希望对新手朋友有点帮助,有问题可以留言。