我知道這個問題經常被問到,我已經應用了許多代碼,但仍然沒有得到解決方案。在IOS中單擊時更改按鈕文本和背景顏色
我有三個單選按鈕,當我選擇radiobutton1
它顯示了show按鈕,現在我想的是,當用戶點擊radiobutton1
它顯示按鈕,第一個按鈕是預選,如果用戶希望從選項按鈕選擇其他按鈕背景顏色和文字顏色應該改變。
我正在嘗試一些代碼,但只有第一個按鈕的顏色被改變,它不會改變其他按鈕的顏色。我的代碼是:
-(void)btnClick:(UIButton *)sender{
switch (sender.tag) {
case 1:
if ([rd1 isSelected]==YES) {
[rd1 setSelected:YES];
}
else{
[rd1 setSelected:YES];
[rd2 setSelected:NO];
[rd3 setSelected:NO];
_house.hidden=NO;
_flat.hidden=NO;
_upperP.hidden=NO;
_lowerP.hidden=NO;
_farmH.hidden=NO;
_roomB.hidden=NO;
_pentH.hidden=NO;
_resident.hidden=YES;
_commercial.hidden=YES;
_agricult.hidden=YES;
_industry.hidden=YES;
_plot.hidden=YES;
_plotF.hidden=YES;
_office.hidden=YES;
_shop.hidden=YES;
_wareH.hidden=YES;
_factory.hidden=YES;
_building.hidden=YES;
_other.hidden=YES;
if ([_house isSelected]==YES) {
House=_house.titleLabel.text;
NSLog(@"Button is %@",House);
_flat.enabled=NO;
_upperP.enabled=NO;
_lowerP.enabled=NO;
_farmH.enabled=NO;
_roomB.enabled=NO;
_pentH.enabled=NO;
}
else if ([_flat isSelected]==YES) {
_house.enabled=NO;
_upperP.enabled=NO;
_lowerP.enabled=NO;
_farmH.enabled=NO;
_roomB.enabled=NO;
_pentH.enabled=NO;
}
[self BgColor];
}
break;
case 2:
if ([rd2 isSelected]==YES) {
[rd2 setSelected:NO];
}
else{
[rd2 setSelected:YES];
[rd1 setSelected:NO];
[rd3 setSelected:NO];
_resident.hidden=NO;
_commercial.hidden=NO;
_agricult.hidden=NO;
_industry.hidden=NO;
_plot.hidden=NO;
_plotF.hidden=NO;
_house.hidden=YES;
_flat.hidden=YES;
_upperP.hidden=YES;
_lowerP.hidden=YES;
_farmH.hidden=YES;
_roomB.hidden=YES;
_pentH.hidden=YES;
_shop.hidden=YES;
_wareH.hidden=YES;
_factory.hidden=YES;
_building.hidden=YES;
_other.hidden=YES;
_office.hidden=YES;
}
break;
case 3:
if ([rd3 isSelected]==YES) {
[rd3 setSelected:NO];
}
else{
[rd3 setSelected:YES];
[rd2 setSelected:NO];
[rd1 setSelected:NO];
_office.hidden=NO;
_shop.hidden=NO;
_wareH.hidden=NO;
_factory.hidden=NO;
_building.hidden=NO;
_other.hidden=NO;
_house.hidden=YES;
_flat.hidden=YES;
_upperP.hidden=YES;
_lowerP.hidden=YES;
_farmH.hidden=YES;
_roomB.hidden=YES;
_pentH.hidden=YES;
_resident.hidden=YES;
_commercial.hidden=YES;
_agricult.hidden=YES;
_industry.hidden=YES;
_plot.hidden=YES;
_plotF.hidden=YES;
}
break;
default:
break;
}
}
-(void)BgColor{
if ([_house isSelected]==YES) {
[_house setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
_house.backgroundColor=[UIColor redColor];
}
else if (([_flat isSelected]==YES)){
[_flat setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
_flat.backgroundColor=[UIColor redColor];
}
}
實際上,在選擇radiobutton1後顯示的按鈕也沒有顏色變化。 @phi –
你能分享一個項目嗎?或者至少有一些截圖? – phi
我已添加屏幕截圖查看。在屏幕截圖中有一個單選按鈕,下面有一些按鈕,我希望它們在點擊時更改背景和文字顏色。 @phi –