iWizard
iWizard

Reputation: 7114

How to read button tag in IBAction?

I have button:

...

UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
rightButton.tag = myCustomNumber;
[rightButton addTarget:self action:@selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
...

And here is IBAction:

..
-(IBAction)showDetails:(id)sender{

    // here I want to NSLOG button tag

}
...

How to do that?

Upvotes: 4

Views: 5821

Answers (3)

Anshuk Garg
Anshuk Garg

Reputation: 1540

NSLog("%d", (UIButton *)sender.tag);

sender is an UIButton object. hope it helps. happy coding :)

Upvotes: 2

Alex Salom
Alex Salom

Reputation: 3094

If showDetails is always called from a UIButton you could change the name of the method to:

- (IBAction)showDetails:(UIButton *)sender {
        NSLog(@"%i", (UIButton *)sender.tag);
}

Remember to perform this change also at the interface file

However, if you use showDetails from different IBAction elements you will have to introspect and check if sender is a UIButton:

- (IBAction)showDetails:(id)sender {
       if ([sender isKindOfClass:[UIButton class]]
       NSLog(@"%i", (UIButton *)sender.tag);
}

Edit: The reason of doing this is that in the way you wrote the code, sender has a dynamic type id and it doesn't have any tag property.

Upvotes: 3

Mathieu Hausherr
Mathieu Hausherr

Reputation: 3485

Just cast your sender to UIControl

-(IBAction)showDetails:(UIControl *)sender {

    // here I want to NSLOG button tag
    NSLog(@"%d",sender.tag);

}

Upvotes: 11

Related Questions