iOS for迴圈建立UIButton及點選處理
{
//宣告一個全域性變數判斷選中的按鈕
UIButton *selectedBtn;
}
- (void)addButton:(UIView *)view{
NSArray *arr = @[@"1",@"5",@"10",@"20",@"50"];
CGFloat w =0;//儲存前一個button的寬以及前一個button距離螢幕邊緣的距離
CGFloat h = 200;//用來控制button距離父檢視的高
for (int i =0; i < arr.count; i++) {
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem
button.layer.cornerRadius=5;
button.layer.masksToBounds =YES;
button.tag = i+1;
//預設選中第一個
if (button.tag==1) {
button.backgroundColor = [UIColorredColor];
selectedBtn=button;
}else{
button.backgroundColor = [UIColorwhiteColor
}
[button addTarget:selfaction:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];[buttonsetTitleColor:[UIColorcolorWithRed:0.000green:0.502blue:1.000alpha:1.000]forState:UIControlStateNormal];
//獲取字號
NSDictionary *attributes =
@{NSFontAttributeName:[UIFontsystemFontOfSize
//根據計算文字的大小
CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(320,2000)options:NSStringDrawingUsesLineFragmentOriginattributes:attributescontext:nil].size.width;
//為button賦值
[buttonsetTitle:[NSStringstringWithFormat:@"%@元",arr[i]]forState:UIControlStateNormal];
//設定button的frame
length=45;//此行固定寬度取消調此行恢復自動計算Tittle長度
button.frame =CGRectMake(10 + w, h, length +15 , 50);
//當button的位置超出螢幕邊緣時換行 320只是button所在父檢視的寬度
if(10 + w + length +15 > view.frame.size.width){
w = 0;//換行時將w置為0
h = h + button.frame.size.height + 10;//距離父檢視也變化
button.frame =CGRectMake(15 + w, h, length +15, 50);//重設button的frame
}
w = button.frame.size.width + button.frame.origin.x;
[view addSubview:button];
}
}
//點選事件
- (void)handleClick:(UIButton *)btn{
NSLog(@"點選了%ld",btn.tag);
//選中變紅色 其他按鈕變為白色
if (selectedBtn) {
selectedBtn.backgroundColor = [UIColorwhiteColor];
}
selectedBtn = btn;
selectedBtn.backgroundColor = [UIColorredColor];
}