![](https://img.haomeiwen.com/i1858529/8c6f28146722bc5f.png)
九宫格的计算就是要知道行数和列数
// 数据
NSArray *images = @[@"publish-video", @"publish-picture", @"publish-text", @"publish-audio", @"publish-review", @"publish-offline"];
NSArray *titles = @[@"发视频", @"发图片", @"发段子", @"发声音", @"审帖", @"离线下载"];
// 添加6个按钮
int maxCols = 3;
CGFloat buttonW = 72;
CGFloat buttonH = buttonW + 30;
CGFloat buttonStarY = (BSScreenH - 2 * buttonH) * 0.5;
CGFloat buttonStarX = 20;
CGFloat xMargin = (BSScreenW - 2 * buttonStarX - maxCols * buttonW) / (maxCols - 1);
for (int i = 0; i < images.count; i++) {
BSVerticalButton *button = [[BSVerticalButton alloc] init];
// 设置内容
button.titleLabel.font = [UIFont systemFontOfSize:14];
[button setTitle:titles[i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
// 设置frame
button.width = buttonW;
button.height = buttonH;
// 九宫格计算
/*
0 1 2
3 4 5
6 7 8
*/
int row = i / maxCols; // 行
int col = i % maxCols; // 列
button.x = buttonStarX + col * (xMargin + buttonW);
button.y = buttonStarY + row * buttonH;
[self.view addSubview:button];
网友评论