iOS開發中的九宮格佈局
效果圖:
程式碼實現:
建立MyTableViewCell繼承於UITableViewCell,然後在MyTableViewCell.m裡
#define KCityButtonWidth (KWidth - 75)/4
#import "MyTableViewCell.h"
@implementation MyTableViewCell
-(void)myTableViewCellAddData{
cityArray = @[@"北京",@"上海",@"廣州",@"杭州",
for (int i = 0; i < cityArray.count; i++) {
//cityButton所在的行
NSInteger row = i / 4;
//cityButton所在的列
NSInteger col = i % 4
cityButton = [UIButton buttonWithType:UIButtonTypeCustom];
cityButton.frame = CGRectMake(15 + (KCityButtonWidth + 15) * col, 42 * row, KCityButtonWidth, 27);
cityButton.layer.borderWidth = 0.5;
cityButton.tag = 200 + i;
[cityButton addTarget:self action:@selector(selectCity:) forControlEvents:UIControlEventTouchUpInside];
cityButton.titleLabel.font = [UIFont systemFontOfSize:12.0];
[cityButton setTitle:cityArray[i] forState:UIControlStateNormal];
[cityButton setTitleColor:[UIColor hex_3A3B3C_Color] forState:UIControlStateNormal];
[self.contentView addSubview:cityButton];
//預設選中第一個cityButton
if (cityButton.tag == 200) {
cityButton.backgroundColor = [UIColor hex_DFDFDF_Color];
[cityButton setTitleColor:[UIColor hex_C2C2C2_Color] forState:UIControlStateNormal];
cityButton.layer.borderColor = [UIColor hex_DFDFDF_Color].CGColor;
} else {
cityButton.backgroundColor = [UIColor clearColor];
[cityButton setTitleColor:[UIColor hex_3A3B3C_Color] forState:UIControlStateNormal];
cityButton.layer.borderColor = [UIColor hex_C2C2C2_Color].CGColor;
}
}
}
-(void)selectCity:(UIButton*)sender{
for (NSInteger i = 0; i < cityArray.count; i++) {
UIButton* selectedCity = [self.contentView viewWithTag:200+i];
if (i == sender.tag-200) {
selectedCity.backgroundColor = [UIColor hex_DFDFDF_Color];
[selectedCity setTitleColor:[UIColor hex_C2C2C2_Color] forState:UIControlStateNormal];
selectedCity.layer.borderColor = [UIColor hex_DFDFDF_Color].CGColor;
}else{
selectedCity.backgroundColor = [UIColor clearColor];
[selectedCity setTitleColor:[UIColor hex_3A3B3C_Color] forState:UIControlStateNormal];
selectedCity.layer.borderColor = [UIColor hex_C2C2C2_Color].CGColor;
}
}
}
@end
在相應Controller中返回MyTableViewCell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (cityArray.count%4 != 0) {
return 42 * ((cityArray.count/4) + 1);
} else {
return 42 * (cityArray.count/4);
}
}