/** 在此我们使用的是Button来做 因为很多时候需要文字也需要图片显示,所以Button比较合适 */ - (void)CreatorBtn { //列数 NSInteger column = 4; //按钮个数 NSInteger buttonCount = 18; //按钮的宽高 CGFloat buttonW = self.view.frame.size.width / column; CGFloat buttonH = buttonW; for (int i = 0; i < buttonCount; i++) { UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(((i % column) * buttonW), ((i / column) * buttonH), buttonW - 10, buttonH - 10); NSLog(@"%@",NSStringFromCGRect(btn.frame)); [btn setBackgroundColor:[UIColor redColor]]; //绑定tag,后边监听点击 btn.tag = i; [self.view addSubview:btn]; //监听按钮点击 [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside]; } } - (void)btnAction:(UIButton *)btn { //根据按钮的tag来监听点击 NSLog(@"点击了第%ld个按钮",(long)btn.tag); }