2011-09-01 77 views
0

我有兩個UIButtons。它們表現得像複選框(兩個按鈕都可以一次選擇)。但我想只有一個按鈕可以選擇在(如單選按鈕)。我該怎麼做? 這是我如何實現複選框按鈕功能。如何實現單選按鈕行爲?

if ([btnAnswer1 isSelected]) { 
     [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState:UIControlStateNormal]; 
     [btnAnswer1 setSelected:NO]; 

    }else { 
     [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected]; 
     [btnAnswer1 setSelected:YES]; 
    } 



    if ([btnAnswer2 isSelected]) { 
     [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState:UIControlStateNormal]; 
     [btnAnswer2 setSelected:NO]; 
    }else { 
     [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected]; 
     [btnAnswer2 setSelected:YES]; 
    } 
+1

也許,使用'UISegmentedControl'會更好? – kpower

+0

閱讀此博客.... http://www.developers-life.com/radio-buttons-in-iphone-application.html它可以幫助你... – PJR

回答

1

雖然我還沒有檢查,只是給出修改後的代碼試試。

if ([btnAnswer1 isSelected]) 
    { 
     [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState:UIControlStateNormal]; 
     [btnAnswer1 setSelected:NO]; 
     selected = FALSE; 
     [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState :UIControlStateSelected]; 
     [btnAnswer2 setSelected:YES]; 
    } 
    else 
    { 
     [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateSelected]; 
     [btnAnswer1 setSelected:YES]; 
     [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState: UIControlStateNormal]; 
     [btnAnswer2 setSelected:NO]; 
     selected = TRUE; 
    } 

    if ([btnAnswer2 isSelected]) 
    { 
     [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState: UIControlStateNormal]; 
     [btnAnswer2 setSelected:NO]; 
     [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateSelected]; 
     [btnAnswer1 setSelected:YES]; 
    } 
    else 
    { 
     [btnAnswer2 setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState: UIControlStateSelected]; 
     [btnAnswer2 setSelected:YES]; 
     [btnAnswer1 setBackgroundImage:[UIImage imageNamed:@"checkbox_unchecked.png"] forState: UIControlStateNormal]; 
     [btnAnswer1 setSelected:NO]; 
    } 
2

我通常實施單選按鈕的方法是:

-(void) radioButtonWasSelected:(RadioButton*) which 
{ 
    //set all radio buttons to unselected 
    //set 'which' to selected 

    //do something with 'which' 

} 
相關問題