九宫格在iOS项目UI中是经常会出现的,在这里写了一个简单的for循环创建九宫格,供新手参考。
#pragma mark - createNineSquare
- (void)createNineSquare {
UIView *btnViewBackground = [[UIView alloc] initWithFrame:CGRectMake(0, bannerImageView.size.height, kDeviceWidth, 3*(kDeviceWidth-3)/4)];
btnViewBackground.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:btnViewBackground];
CGFloat btnMargin = 1; //间隔
CGFloat btnWidth = (kDeviceWidth-3)/4; //宽
CGFloat btnHeight = (kDeviceWidth-3)/4; //高
for (int i = 0; i<12; i++) {
int row = i/4; //行
int col = i%4; //列
btnView = [[UIView alloc] init];
btnView.frame = CGRectMake(col*(btnWidth + btnMargin), row*(btnHeight + btnMargin), btnWidth, btnHeight);
btnView.backgroundColor = [UIColor whiteColor];
[btnViewBackground addSubview:btnView];
UIImageView *btnImageView = [[UIImageView alloc] initWithFrame:CGRectMake(btnWidth/3, 15, btnWidth/3, btnWidth/3)];
btnImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",self.btnImageArray[i]]];
[btnView addSubview:btnImageView];
UILabel *btnLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, btnWidth/3+25, btnWidth, 30)];
btnLabel.backgroundColor = [UIColor clearColor];
btnLabel.textAlignment = NSTextAlignmentCenter;
btnLabel.textColor = [UIColor blackColor];
btnLabel.text = [NSString stringWithFormat:@"%@",self.btnLabelTitleArray[i]];
btnLabel.font = kSystemFont_14;
[btnView addSubview:btnLabel];
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(col*(btnWidth + btnMargin), row*(btnHeight + btnMargin), btnWidth, btnHeight);
button.backgroundColor = [UIColor clearColor];
button.tag = 1000+i;
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[btnViewBackground addSubview:button];
}
}
这是一个简单的九宫格类型的Button 以及对应的图片和标题。