在許多應用中,我們會需要動態產生一整排按鈕(例如玩法選項、分類標籤等),並讓使用者能點擊切換選取狀態。本文示範如何用迴圈排列按鈕,並透過 tag 精準回應每顆按鈕的點擊事件。
先準備按鈕要顯示的文字陣列,再以巢狀迴圈依行列座標逐一建立按鈕,透過 tag 為每顆按鈕標上唯一編號,方便後續辨識:
// 彩種按鈕
listChuan = 1;
NSMutableArray *showLabelArray = [NSMutableArray arrayWithCapacity:10];
for (int i = 0; i < 7; i++) {
listChuan++;
NSString *chuanStr = [NSString stringWithFormat:@"%i選", listChuan];
[showLabelArray addObject:chuanStr];
}
// 添加彩種按鈕
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
if (i == 1 && j == 3) {
break;
}
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageNamed:@"btn_white_small"] forState:UIControlStateNormal];
[btn setTitle:[showLabelArray objectAtIndex:i*4+j] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
btn.layer.borderWidth = 0.7;
btn.selected = NO;
btn.frame = CGRectMake(5+j*70, 50+i*40, 60, 30);
btn.tag = i*4+j;
[btn addTarget:self action:@selector(chooseLottery:) forControlEvents:UIControlEventTouchUpInside];
[chooseBackroundView addSubview:btn];
}
}
在回呼方法中,透過 sender 取得被點擊的按鈕,再切換它的 selected 狀態,即可達到多選的效果:
-(void)chooseLottery:(UIButton *)sender{
UIView *backBround = (UIView *)[self.view viewWithTag:TOUZHUBACKGROUNVIEW_Tag];
UIButton *button = (UIButton *)sender;
// 切換選取狀態
button.selected = !button.selected;
}
frame 計算,能輕鬆完成多行多列的按鈕排列。tag,是後續精準定位與操作的關鍵。selected 屬性,即可實作直覺的多選互動。掌握這個模式後,就能靈活應用於各種需要動態產生大量可互動元件的場景。