user3892683
user3892683

Reputation:

UIbutton with multiple argument selector?

I am coding in Xcode 6.1.1 and with objective-c. I want to have multiple buttons who all call the same method. Normally I would do something like this:

[button addTarget:self action:@selector(button_method) forControlEvents:UIControlEventTouchUpInside];

What I would like to do is when I touch an button the button sends itself to a method. Something like this (OF COURSE THIS IS WRONG):

[button2 addTarget:self action:[button2 performSelector:@selector(method2:) withObject:button2] forControlEvents:UIControlEventTouchUpInside];

And in the method do something like this:

-(void)add_group:(UIButton*)button{
  button.backgroundcolor=[UIColor greencolor];

}

Question: What would be the right way to call a method from a button with itself as argument?

Upvotes: 0

Views: 820

Answers (2)

Ian MacDonald
Ian MacDonald

Reputation: 14000

addTarget:action:forControlEvents: accepts selectors with up to two arguments. The following will all fire correctly:

[button addTarget:self action:@selector(action1) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:@selector(action2:) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:@selector(action3:event:) forControlEvents:UIControlEventTouchUpInside];

for handlers as such:

- (void)action1 {
  //...
}
- (void)action2:(UIControl *)control {
  //...
}
- (void)action3:(UIControl *)control event:(UIEvent *)event {
  //...
}

In most cases, the event parameter is unused in applications, so you'll typically only see examples of action1 or action2 in source code. For your particular usage, you'll want to use the action2 style. You can change the parameter type to UIButton * or any other subclass of UIControl if you want.

Upvotes: 2

croX
croX

Reputation: 1725

Your first idea is almost the best. When using the addTarget:action:forControlEvents: method, the action parameter may - if you want - additionally include the sender automatically as said in the documentation:

The action message may optionally include the sender and the event as parameters, in that order.

So simply keep your add_group: method as it is and make the following statement:

[button addTarget:self action:@selector(add_group:) forControlEvents:UIControlEventTouchUpInside];

Your object button will than be automatically passed to the action method add_group:. Don't forget the colon!

Upvotes: 1

Related Questions