Can I use a string from an array as a selector in Swift?

我的梦境 提交于 2019-12-02 01:17:34

What you are trying to do is totally legit – you can indeed convert a string to a selector, then pass that selector to a menu item.

You're however trying to use the selector literal syntax to initialise a Selector, giving that language construct a Selector as an argument (which is just syntactically wrong), where in fact you can just pass the Selector returned by NSSelectorFromString to the NSMenuItem initialiser call.

The selector literal syntax #selector is used when you have a "fixed" selector in mind that you want to create a Selector for (for instance an instance method of the class you are in). The NSSelectorFromString is intended for this kind of cases like yours where the selector is a variable (now that in Swift 2.2 there is indeed some syntax given for #selector literals!)

import Cocoa

class MenuArrayObject
{
    var title: String = "Foo"
    var subMenuTitles: [String] = ["foo"]
    var subMenuSelectors:  [String] = ["foobar"]
}

let menuArrayObject = MenuArrayObject()

let indexMenu = NSMenu()

for (i, submenuTitle) in menuArrayObject.subMenuTitles.enumerate() {
    let selectorStr = menuArrayObject.subMenuSelectors[i]
    let selector = NSSelectorFromString(selectorStr)
    let item = NSMenuItem(title: submenuTitle, action: selector, keyEquivalent: "")

    indexMenu.addItem(item)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!