Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSButton setAction selector

Tags:

cocoa

nsbutton

I just want to add a NSButton with setAction Arguments.

NSRect frame = NSMakeRect(10, 40, 90, 40);  
NSButton* pushButton = [[NSButton alloc] initWithFrame: frame];  
[pushButton setTarget:self];   
[pushButton setAction:@selector(myAction:)];

But I want to put an argument to the function myAction...
How ?
Thanks.

like image 723
Simon V. Avatar asked Feb 18 '23 00:02

Simon V.


2 Answers

But I want to put an argument to the function myAction...
How ?

You can't.

… if there is more than one button that uses this method, we can not differentiate the sender (only with title)...

There are three ways to tell which button (or other control) is talking to you:

  • Assign each button (or other control) a tag, and compare the tags in your action method. When you create controls in a nib, this has the downside that you have to write the tag twice (once in the code, once in the nib). Since you're writing out the button by hand from scratch, you don't have that problem.
  • Have an outlet to every control that you expect to send you this message, and compare the sender to each outlet.
  • Have different action methods, with each control being the only one wired up to each action. Each action method then does not need to determine which control sent you that message, because you already know that by which method it is.

The problem with tags is the aforementioned repetitiveness. It's also very easy to neglect to name each tag, so you end up looking at code like if ([sender tag] == 42) and not knowing/having to look up which control is #42.

The problem with outlets is that your action method may get very long, and anyway is probably doing multiple different things that have no business being in the same method. (Which is also a problem with tags.)

So, I generally prefer the third solution. Create an action method for every button (or other control) that will have you as its target. You'll typically name the method and the button the same (like save: and “Save”) or something very similar (like terminate: and “Quit”), so you'll know just by reading each method which button it belongs to.

like image 171
Peter Hosey Avatar answered Mar 23 '23 06:03

Peter Hosey


I never programatically created an NSButton, but I think that you just need to create a method like this:

- (void) myAction: (NSButton*)button{
    //your code
}

And that's it !!

like image 28
GreatGoldApps Avatar answered Mar 23 '23 05:03

GreatGoldApps