I want to send doSomething
to the firstResponder
, which could be any of several objects.
menuItem = NSMenuItem(title: "Do Something!",
action: Selector("doSomething"),
keyEquivalent: "")
I was using Selector("doSomething")
prior to Swift 2.2. How do I do it now?
Create a protocol with the Selector doSomething
and have all of your objects that can be first responders conform to it. Then implement the selector for your classes.
@objc protocol MyProtocol {
func myCoolFuncThatManyObjectsRespondTo()
}
extension NSObject: MyProtocol {
func myCoolFuncThatManyObjectsRespondTo() {
print("Sup?")
}
}
let menuItem = NSMenuItem(title: "Do Something!", action: #selector(MyProtocol.myCoolFuncThatManyObjectsRespondTo), keyEquivalent: "")
#selector({classname}.{methodname}{signature})
func doSomething() {}
#selector(MyClass.doSomething)
func doSomething(arg: String) {}
#selector(MyClass.doSomething(_:))
func doSomething(arg: String, withSomething something: Int) {}
#selector(MyClass.doSomething(_:withSomething:))
Note that the selected method must be bridged to Objective-C, so either MyClass
should extend NSObject
or add @objc
annotation to the method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.