JCurativo
JCurativo

Reputation: 713

How to get tags of many UIButtons but with same action selector

I have a method that shows 10 (or more) UIButtons. I have here a code as to how I showed these buttons..

-(void)showButtons{
for(int i = 0; i < 10; i++){
  UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
  button.frame = CGRectMake(x, y, 100, 94);  //Assume x and y have values
  **button.tag = i + 1000;**
  [button setBackgroundImage:[_cardImages objectAtIndex:i]  
      forState:UIControlStateNormal];
  [button addTarget:self action:@selector(myMethod:)   
      forControlEvents:UIControlEventTouchUpInside];
  [self.view add subview:button];
  [button release];

} }

-(IBAction)myMethod:(id)sender{
// I would like to print here button.tag, but I always get an error

}

Upvotes: 0

Views: 905

Answers (4)

HarshIT
HarshIT

Reputation: 4915

Your myMethod's defination should be like this

I use the same way to get tag of sender.

-(IBAction)myMethod:(id)sender
{
   NSLog(@"%d",[sender tag]);
}

No type casting is needed, you may get tag of sender, it doesn't matter the datatype of it.

Upvotes: 0

Marco Mempin
Marco Mempin

Reputation: 51

Try accessing the UIButton's UIView and then accessing it's TAG property. So modifying Amresh Kumar's code:

-(IBAction)myMethod {
 UIButton *pressedButton = (UIButton *)sender;
 NSLog(@"Tag of button pressed:%d",pressedButton.view.tag);
}

Upvotes: 0

Amresh Kumar
Amresh Kumar

Reputation: 1445

You need to typecast the sender here because id types don't have the tag property.
The new code will be


-(IBAction)myMethod:(id)sender{
   UIButton *pressedButton = (UIButton *)sender;
   NSLog(@"Tag of button pressed:%d",pressedButton.tag);
}

Upvotes: 3

Gypsa
Gypsa

Reputation: 11314

You will get the result by printing value of sender.tag instead of button.tag

-(IBAction)myMethod:(id)sender{
NSLog(@"%d",sender.tag);
}

Upvotes: 0

Related Questions