通过带参数的#selector 调用函数
Calling a function through #selector with parameters
我想调用一个函数并使用 #selector
为其提供参数。但是,我收到错误消息:
"Argument of '#selector' does not refer to an '@objc' method, property, or initializer"
@objc func changeCrypto(crypto: String) {
//stuff
}
func constructMenu() {
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Bitcoin", action: #selector(changeCrypto(crypto: "bitcoin")), keyEquivalent: "B"))
menu.addItem(NSMenuItem(title: "Ethereum", action: #selector(changeCrypto(crypto: "ethereum")), keyEquivalent: "E"))
menu.addItem(NSMenuItem(title: "Litecoin", action: #selector(changeCrypto(crypto: "litecoin")), keyEquivalent: "L"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit It", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
statusItem.menu = menu
}
我修好了!我把它改成了下面的..
@objc func changeCrypto(_ sender: NSMenuItem) {
//Here I call the title of the Menu Item pressed
print(sender.title)
}
func constructMenu() {
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Bitcoin", action: #selector(changeCrypto(_:)), keyEquivalent: "B"))
menu.addItem(NSMenuItem(title: "Ethereum", action: #selector(changeCrypto(_:)), keyEquivalent: "E"))
menu.addItem(NSMenuItem(title: "Litecoin", action: #selector(changeCrypto(_:)), keyEquivalent: "L"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit It", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
statusItem.menu = menu
}
我想调用一个函数并使用 #selector
为其提供参数。但是,我收到错误消息:
"Argument of '#selector' does not refer to an '@objc' method, property, or initializer"
@objc func changeCrypto(crypto: String) {
//stuff
}
func constructMenu() {
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Bitcoin", action: #selector(changeCrypto(crypto: "bitcoin")), keyEquivalent: "B"))
menu.addItem(NSMenuItem(title: "Ethereum", action: #selector(changeCrypto(crypto: "ethereum")), keyEquivalent: "E"))
menu.addItem(NSMenuItem(title: "Litecoin", action: #selector(changeCrypto(crypto: "litecoin")), keyEquivalent: "L"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit It", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
statusItem.menu = menu
}
我修好了!我把它改成了下面的..
@objc func changeCrypto(_ sender: NSMenuItem) {
//Here I call the title of the Menu Item pressed
print(sender.title)
}
func constructMenu() {
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Bitcoin", action: #selector(changeCrypto(_:)), keyEquivalent: "B"))
menu.addItem(NSMenuItem(title: "Ethereum", action: #selector(changeCrypto(_:)), keyEquivalent: "E"))
menu.addItem(NSMenuItem(title: "Litecoin", action: #selector(changeCrypto(_:)), keyEquivalent: "L"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit It", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
statusItem.menu = menu
}