先說一下原理,就是利用中間變量來記錄某個選中狀態的按鈕,加一個判斷,如果用戶下一次點擊的不是這個按鈕那么用中間變量把這個按鈕的選中狀態取消掉,再把新的按鈕賦值給中間變量,這能保證選中狀態的惟一性。這里是OC 應用在iOS 項目中的,下面來看具體實現。
首先我們先定義一個中間變量
@property (strong,nonatomic)UIButton * tmpBtn;
然后在ViewDidLoad方法里,創建四個按鈕,設置它們屬性,以及點擊方法,在此外設置中間變量tmpBtn = nil;
—(void)viewDidLoad{ NSArray * array = [NSArray arrayWithObjects:@"默認",@"銷量",@"價格",@"時間", nil]; for (int i = 0; i<4; i ++) { UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(80*i, 0, 80, 40)]; [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal]; [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected]; [button.titleLabel setFont:[UIFont systemFontOfSize:14]]; [button.layer setBorderWidth:0.3]; button.userInteractionEnabled = YES; [button addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside]; [button setBackgroundColor:[UIColor whiteColor]]; [button setTag:i]; [self.view addSubview:button]; }
下面來看buttonselected:里面的實現過程
-(void)buttonSelected:(UIButton*)sender{ if (_tmpBtn == nil){ sender.selected = YES; _tmpBtn = sender; } else if (_tmpBtn !=nil && _tmpBtn == sender){ sender.selected = YES; } else if (_tmpBtn!= btn && _tmpBtn!=nil){ _tmpBtn.selected = NO; sender.selected = YES; _tmpBtn = btn; } }