iOS代码实现九宫格

时间:2022-09-25 08:09:22
#define ScreenW [UIScreen mainScreen].bounds.size.width
#define ScreenH [UIScreen mainScreen].bounds.size.height
 // 数据
NSArray *images = @[@"publish-boke", @"publish-weixin", @"publish-QQ", @"publish-offline"];
NSArray *titles = @[@"发博客", @"发微信", @"发QQ",@"离线下载"]; // 中间的6个按钮
int maxCols = ;
CGFloat buttonW = ;
CGFloat buttonH = buttonW + ;
CGFloat buttonStartY = (ScreenH - * buttonH) * 0.5;
CGFloat buttonStartX = ;
CGFloat xMargin = (ScreenW - * buttonStartX - maxCols * buttonW) / (maxCols - );
for (int i = ; i<images.count; i++) {
VerticalButton *button = [[VerticalButton alloc] init];
// 设置内容
button.titleLabel.font = [UIFont systemFontOfSize:];
[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;
int row = i / maxCols;
int col = i % maxCols;
button.x = buttonStartX + col * (xMargin + buttonW);
button.y = buttonStartY + row * buttonH;
[self.view addSubview:button];
}