Frage

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?

War es hilfreich?

Lösung

You can connect more than one button to the same action method in Xcode. After creating and connecting the first action, control-drag the remaining buttons to the existing action in the .h file:

enter image description here

Then you can assign different tags to the buttons in the Attributes Inspector, and check [sender tag] in the action method.

If you create a new action with the same name, Xcode creates another method with the same name, which will cause compiler errors due to "duplicate declarations".

Andere Tipps

It looks like you are trying to Copy-Paste this Sample into your Code and it's not working, right ? You should provide Frame to the Buttons.

Here is the Working Code :

for( int i = 0; i < 5; i++ ) 
{
    UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    aButton.frame = CGRectMake(10 + i*50,10,50,50);
    [aButton setTag:i];
    [aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:aButton];
}

Here, frame should not be static otherwise the Buttons will be overlapped.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top