hanumanDev hanumanDev - 3 months ago 8x
Objective-C Question

How to get the title for a UIButton when it is pressed

I'm trying to discover what the UIButton title is for which UIButton was pressed in the following code.

on viewDidLoad the button title is outputted to the console using:

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

I would like to get this title when a button is pressed instead.

thanks for any help


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



In your action:

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

Edit: Or as commented Iulian: sender.currentTitle, but it may be nil, see the comments of Michael.