#define ROW 5
#define COL 5
#define COUNTS ROW*COL
//创建5*5的按钮
- (void)creatButtons{
int btnWidth = 58;
int btnHeight = 30;
int btnSpace = 5;
int btnX = (self.view.bounds.size.width - (btnWidth*ROW + btnSpace*(ROW-1)))/2;
int btnY = (self.view.bounds.size.height - (btnHeight*COL + btnSpace*(COL-1)))/2;
for (int i=0; i<COUNTS; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setBackgroundColor:[UIColor whiteColor]];
[btn setTitle:[NSString stringWithFormat:@"%d",i+1]forState:UIControlStateNormal];
[btn setTitle:[NSString stringWithFormat:@"%d",i+1]forState:UIControlStateHighlighted];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[btn setTag:i+1];
CGRect frame;
frame.origin.x = (i%ROW)*(btnWidth+btnSpace)+btnX;
frame.origin.y = (i/COL)*(btnHeight+btnSpace)+btnY;
frame.size.width = btnWidth;
frame.size.height = btnHeight;
[btn setFrame:frame];
[btn addTarget:self action:@selector(touchDown:)forControlEvents:UIControlEventTouchDown];
[btn addTarget:self action:@selector(btnAction:)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
}
//按钮按下
- (void)touchDown:(id)sender{
UIButton *btn = sender;
[btn setBackgroundColor:[UIColor redColor]];
}
//按钮按下松开
- (void)btnAction:(id)sender{
UIButton *btn = sender;
[btn setBackgroundColor:[UIColor whiteColor]];
NSLog(@"%d",btn.tag);
}