hanumanDev
hanumanDev

Reputation: 6614

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

        }

Upvotes: 12

Views: 39928

Answers (3)

user4993619
user4993619

Reputation:

NSString * strButtonTitle = [btnButton titleForState:state];

where state:

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

For your requirement

NSString * strButtonTitle = [btnButton titleForState:UIControlStateSelected];

This is the method for getting the title for different states of button at any given time in the program...But based on the question answer from Zaphod is good.

Upvotes: 4

Zaphod
Zaphod

Reputation: 7290

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.

Upvotes: 28

Fogmeister
Fogmeister

Reputation: 77661

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

Upvotes: 11

Related Questions