4

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?

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
iWizard
  • 6,816
  • 19
  • 67
  • 103

3 Answers3

11

Just cast your sender to UIControl

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

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

}
Mathieu Hausherr
  • 3,485
  • 23
  • 30
3

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.

Alex Salom
  • 3,074
  • 4
  • 22
  • 33
2
NSLog("%d", (UIButton *)sender.tag);

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

Anshuk Garg
  • 1,540
  • 12
  • 14