I want to be able to detect which button is pressed. I wonder if there is some UIButton class method which can will be called automatically when a button is pressed, which allows me to find out the text or tag of the button pressed and pass that on to a variable? Or some objective-c event method that does the same?
I know this topic has been posted here before. The common response appears to be that this would be the solution:
In .h file
- (IBAction)buttonClicked:(UIButton *)sender;
In .m file
- (IBAction)buttonPressed:(UIButton *)sender{
// Do something her to display which button pressed
}
I have also seen other examples with names such as buttonPressed, onButtonTao etc.
So I assume that this method must be called from each button. However, this does not work, xcode complains when I try to assign the same method to more than one button.
The following example, posted here at Stack, uses the same action, but programatically:
for( int i = 0; i < 5; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:i];
[aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aView addSubview:aButton];
}
// then ...
- (void)buttonClicked:(UIButton*)button
{
NSLog(@"Button %ld clicked.", (long int)[button tag]);
}
So, what am I missing here, why does xcode not accept the same method for multiple buttons? And is there some other way to detect which button is pressed without connecting a specific action to each and every button?