2013-01-07 49 views
9

我試圖發現UIButton標題是哪個UIButton在下面的代碼中被按下。如何獲得它被按下時UIButton的標題

在viewDidLoad中的按鈕標題輸出到使用控制檯:

 NSLog(@"The button title is %@ ", btn.titleLabel.text); 

我想當按下按鈕,而不是得到這個稱號。

感謝您的幫助

:)

// Create buttons for the sliding category menu. 
     NSMutableArray* buttonArray = [NSMutableArray array]; 
     NSArray * myImages = [NSArray arrayWithObjects:@"category-cafe-unsel.png", @"category-food-unsel.png", @"category-clothing-unsel.png", @"category-health-unsel.png", @"category-tech-unsel_phone.png" , @"category-tech2-unsel.png", @"catefory-theatre-unsel.png", @"category-travel-unsel.png", nil]; 

     // only create the amount of buttons based on the image array count 
     for(int i = 0;i < [myImages count]; i++) 
     { 
      // Custom UIButton 

      btn = [UIButton buttonWithType:UIButtonTypeCustom]; 

      [btn setFrame:CGRectMake(0.0f, 20.0f, 52.0f, 52.0f)]; 
      [btn setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal]; 
      [btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal]; 

      NSLog(@"The button title is %@ ", btn.titleLabel.text); 

      [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
      [buttonArray addObject:btn]; 

      NSLog(@"Button tag is: %d",btn.tag); 

     } 

回答

22

在你的動作中:

- (void) buttonPressed:(UIButton*) sender { 
    NSLog(@"The button title is %@",sender.titleLabel.text); 
} 

編輯: 或者正如評論尤利安:sender.currentTitle,但它可能是nil,看到邁克爾的意見。

+0

這和'sender.currentTitle'有什麼區別? –

+0

無。你說得對,我會編輯答案。 – Zaphod

+0

我沒有說這不是,我只是問。剛纔'currentTitle'是'nil',但'titleLabel.text'不是。 –

11

你應該有地方的功能...

- (void)buttonPressed:(id)sender 

只是把這個裏面......

- (void)buttonPressed:(id)sender 
{ 
    UIButton *someButton = (UIButton*)sender; 

    NSLog(@"The button title is %@ ", [someButton titleForState:UIControlStateNormal]); 

    //You should also be able to use... 
    //NSLog(@"The button title is %@ ", someButton.titleLabel.text); 
} 
3
NSString * strButtonTitle = [btnButton titleForState:state]; 

其中狀態:

UIControlStateNormal, 
UIControlStateHighlighted, 
UIControlStateDisabled, 
UIControlStateSelected, 
UIControlStateFocused, 
UIControlStateApplication, 
UIControlStateReserved 

您的需求

NSString * strButtonTitle = [btnButton titleForState:UIControlStateSelected]; 

這是獲得冠軍按鈕的不同狀態在程序中任何給定時間的方法...但基於從Zaphod是好的問題的答案。

相關問題