Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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 !!

  • .tag should be sufficient if your object have any integer uniqueID.
  • I use .identifier instead, since it support string based uniqueID.

Example:

...
for (index, app) in apps.enumerated() {
    let appButton = NSButton(title: app.title, target: self, action: #selector(appButtonPressed))
    appButton.identifier = NSUserInterfaceItemIdentifier(rawValue: app.guid)
}

...
@objc func appButtonPressed(sender: NSButton) {
    print(sender.identifier?.rawValue)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top