九宫格布局
#import "ViewController.h"
#define kViewW 57
#define kViewH 57
#define kNum 3
#define kTotal 8
#define kStart 50 //状态栏高度
@interface ViewController ()
@property (nonatomic,strong) NSArray *picNameArr;
@property (nonatomic,strong) NSArray *tittleNameArr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_picNameArr = @[@"account_setting.png",@"account_favorite.png",@"account_user.png",@"account_collect.png",@"account_download.png",@"account_comment.png",@"account_help.png",@"account_candou.png"];
_tittleNameArr = @[@"我的设置",@"我的关注",@"我的账户",@"我的收藏",@"我的下载",@"我的评论",@"我的帮助",@"蚕豆应用"];
[self creatUI];
}
-(void)creatUI{
CGFloat marginX = (320-kNum*kViewW)/(kNum+1);//每行中两个按键的间距
CGFloat marginY = 60;//每列中两个按键的间距
for (int i=0; i<kTotal; i++) {
//创建按键用来显示按键图片
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
int row = i % kNum;//每行第几个按键
int col = i / kNum;//第几行
CGFloat x = marginX + (marginX + kViewW) * row;
CGFloat y = kStart + marginY + (marginY + kViewH) * col;
button.frame = CGRectMake(x, y, kViewW, kViewH);
button.tag = i;
[button setImage:[UIImage imageNamed:_picNameArr[i]] forState:UIControlStateNormal];
//创建标签 用来显示按键name
UILabel *lable = [[UILabel alloc] init];
lable.frame = CGRectMake(x, CGRectGetMaxY(button.frame), 57, 20);
lable.text = _tittleNameArr[i];
lable.textColor = [UIColor blackColor];
lable.font = [UIFont systemFontOfSize:12];
lable.textAlignment = NSTextAlignmentCenter;//居中对齐
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:lable];
[self.view addSubview:button];
}
}
-(void)buttonClick:(UIButton *)button{
NSLog(@"%@",_tittleNameArr[button.tag]);
}
@end