如何获得一个UIButton按下时的标题

我试图发现在下面的代码中按下哪个UIButton的UIButton标题是什么。

on viewDidLoadbutton标题输出到控制台使用:

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

当按下button时,我想获得这个标题。

谢谢你的帮助

🙂

 // 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); } 

在你的行动中:

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

编辑 :或作为评论Iulian: sender.currentTitle ,但它可能是nil ,请参阅迈克尔的意见。

你应该有某个地方的function…

 - (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); } 
 NSString * strButtonTitle = [btnButton titleForState:state]; 

哪里状态:

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

为了您的要求

 NSString * strButtonTitle = [btnButton titleForState:UIControlStateSelected]; 

这是在任何给定的时间在程序中获取button的不同状态的标题的方法…但基于来自Zaphod的问题答案是好的。