通过带参数的#selector调用函数

时间:2018-03-23 23:49:51

标签: swift cocoa nsmenuitem

我想要调用一个函数并使用#selector为其指定参数。但是,我收到错误:

  

"' #selector'并不是指' @ objc'方法,属性或初始化程序"

@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
}

1 个答案:

答案 0 :(得分:2)

我修好了!我将其更改为以下内容..

@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
}