Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
iWizard Avatar asked Dec 05 '22 16:12

iWizard


2 Answers

Just cast your sender to UIControl

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

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

}
like image 116
Mathieu Hausherr Avatar answered Dec 26 '22 18:12

Mathieu Hausherr


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.

like image 30
Alex Salom Avatar answered Dec 26 '22 17:12

Alex Salom