2012-08-26 38 views
0

至此,我有10個按鈕,並且我在每個按鈕的Title內寫入了一個數字,即0到9.我的問題在於,如何切換按鈕功能,只是說當我按數字0時,該值將顯示在showLabel.text中爲0,並且該按鈕處於選定狀態,但是當我再次按下它時,數字在showLabel.text中消失,並且按鈕將變回正常州。我使用下面的代碼,但它不能解決我的問題。我的意思是,只要說我選擇了數字「1,5,7,8」,我想取消選擇數字5,使用下面的代碼我的showLabel將取代所有數字都不是「1,7,8」。所以我認爲這不是使用此代碼的好主意。如何在XCode中使用currentTitle切換UIButton

-(IBAction)numberBtn:(UIButton *)sender 
{ 
    UIButton *button = (UIButton *)sender; 
    [button setTitle:@"X" forState:UIControlStateSelected]; 
    button.selected = !button.selected; 
    if (button.selected) 
    { 
     number = sender.currentTitle; 
     showLabel.text = [showLabel.text stringByAppendingFormat:number]; 
    } 
    else 
    { 
     showLabel.text = [NSString stringWithFormat:@""]; 
    } 
} 

有沒有辦法做到這一點?節日快樂。

+1

難道只是我還是'的UIButton *鍵=(UIButton的*)發件人;'完全是多餘的? – 2012-08-26 07:46:41

回答

0

好吧。一個想法是建立一個10個布爾值的數組,並且每次按下按鈕 - 您只需要在布爾數組中切換相應的值並使用「for」循環更新您的標籤:

for (int nn=0; nn<10; ++nn) if (boolVals[nn]) [myString appendFormat @"%d ", nn]; 
0

而是執行此操作:

- (IBAction)numberBtn:(UIButton *)sender { 
    sender.selected = !sender.selected; 
    if (sender.selected) 
    { 
     NSString *number = sender.currentTitle; 
     showLabel.text = [showLabel.text stringByAppendingString:number]; 
    } 
    else 
    { 
     NSString *newString; 
     NSString *number = sender.currentTitle; 
     NSString *string = showLabel.text; 
     for (int i = 0; i<string.length; ++i) { 
      NSString *sub = [string substringWithRange:(NSRange){i, 1}]; 
      if ([sub isEqualToString:number]) { 
       newString = [string substringToIndex:i]; 
       newString = [newString stringByAppendingString:[string substringFromIndex:i+1]]; 
      } 
     } 
     showLabel.text = newString; 
    } 
    [sender setTitle:@"X" forState:UIControlStateSelected]; 

}