从Swift 2.2开始,针对编译时检查的选择器有一种特殊的语法。它使用语法:#selector(methodName)
。
var b = UIBarButtonItem(
title: "Continue",
style: .plain,
target: self,
action: #selector(sayHello(sender:))
)
func sayHello(sender: UIBarButtonItem) {
}
如果不确定方法名称应为什么样,则可以使用copy命令的特殊版本,该版本非常有用。将光标放在基本方法名称的某个位置(例如sayHello),然后按Shift
+ Control
+ Option
+ C
。这样就可以在键盘上粘贴“符号名称”。如果还按住Command
,它将复制“ Qualified Symbol Name”(合格符号名称),其中还将包括类型。
var b = UIBarButtonItem(
title: "Continue",
style: .Plain,
target: self,
action: #selector(sayHello(_:))
)
func sayHello(sender: UIBarButtonItem) {
}
这是因为在进行方法调用时,在Swift 2.3中不需要第一个参数名称。
您可以在swift.org上了解有关语法的更多信息:https ://swift.org/blog/swift-2-2-new- features/#compile-time-checked- selectors