Where is NSControl's addTarget() method?

917 views Asked by At

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(_:))
2

There are 2 answers

3
vadian On BEST ANSWER

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

1
dniswhite On

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

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