1

So I haven't looked at Swift/Cocoa in several years. I just created a simple macOS app using Xcode 10.0 and see that NSControl no longer has an addTarget(...) method. It looks like it was replaced by a target property of type id.

How do I go about adding handlers for things like button clicks now since I need to specify the action (e.g. click), object to be called, and the selector to call on that object.


Solution:

let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.button?.target = self
statusItem.button?.action = #selector(didClick(_:))
RobertJoseph
  • 7,968
  • 12
  • 68
  • 113

2 Answers2

1

Right, the method based syntax foo.addTarget(self) has been replaced with the property based syntax foo.target = self. It still exists in UIKit because in Cocoa Touch you have to specify also the control event.

And all relevant NSControl subclasses have init methods to pass target and action

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thank you @vadian. Unfortunately, I'm still a bit confused as I'm not the one creating the button. How do I specify which method gets called, say for a click event, when I'm only indicating that the object to be called is `self` with `foo.target = self`? – RobertJoseph Sep 24 '18 at 14:34
  • 1
    There is also an `action` property to specify the selector. – vadian Sep 24 '18 at 14:39
  • 1
    Did `NSControl` have a `addTarget:` method? As far as I know, `NSControl` always had one target and a `setTarget:` method. – Willeke Sep 25 '18 at 11:13
-2

It's still there... You might want to review the docs as refresher.

https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

dniswhite
  • 176
  • 10