Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

        }
like image 801
hanumanDev Avatar asked Jan 07 '13 15:01

hanumanDev


2 Answers

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.

like image 116
Zaphod Avatar answered Oct 13 '22 21:10

Zaphod


You should have the function somewhere...

- (void)buttonPressed:(id)sender

Just put this inside it...

- (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);
}
like image 24
Fogmeister Avatar answered Oct 13 '22 20:10

Fogmeister