【问题标题】:How to use #selector in Swift 2.2 for the first responder, without a class?如何在没有类的情况下在 Swift 2.2 中为第一响应者使用#selector?
【发布时间】:2024-01-03 00:56:01
【问题描述】:
我想将doSomething 发送到firstResponder,它可以是多个对象中的任何一个。
menuItem = NSMenuItem(title: "Do Something!",
action: Selector("doSomething"),
keyEquivalent: "")
在 Swift 2.2 之前,我使用的是 Selector("doSomething")。我现在该怎么做?
【问题讨论】:
标签:
swift
macos
cocoa
swift2
selector
【解决方案1】:
使用选择器doSomething 创建一个协议,并让所有可以成为第一响应者的对象都符合它。然后为你的类实现选择器。
@objc protocol MyProtocol {
func myCoolFuncThatManyObjectsRespondTo()
}
extension NSObject: MyProtocol {
func myCoolFuncThatManyObjectsRespondTo() {
print("Sup?")
}
}
let menuItem = NSMenuItem(title: "Do Something!", action: #selector(MyProtocol.myCoolFuncThatManyObjectsRespondTo), keyEquivalent: "")
【解决方案2】:
#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:))
请注意,所选方法必须桥接到 Objective-C,因此 MyClass 应扩展 NSObject 或在方法中添加 @objc 注释。