tags:

views:

450

answers:

1

How do i set a tag for a button programmatically?

I later want to compare to tags for a conclusion

ive tried this

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

but that just crashes the app.... :(

any other ideas?

Cheers Guys

Sam

+1  A: 

You need to cast sender as a UIButton:

-(IBAction)buttonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(@"%d", [button tag]);
}

Edit: Regarding the message "unrecognized selector"...

Based on your error message, it's not able to call the buttonPressed method in the first place. Notice in the error message it is looking for "buttonPressed" (no colon at end) but the method is named "buttonPressed:". If you are setting the button target in code, make sure the selector is set to buttonPressed: instead of just buttonPressed. If you are setting the target in IB, the xib may be out of sync with the code.

Also, your original code "[sender tag]" should also work but to access button-specific properties, you'll still need to cast it to UIButton.

DyingCactus
still crashes... :(
Sam Jarman
2010-03-17 16:07:35.322 Memory[37490:207] *** -[MemoryViewController buttonPressed]: unrecognized selector sent to instance 0x3b08cb02010-03-17 16:07:35.324 Memory[37490:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[MemoryViewController buttonPressed]: unrecognized selector sent to instance 0x3b08cb0'stack....
Sam Jarman
[button tag] should work. Please see edits to the answer.
DyingCactus