首页 > 解决方案 > 菜单栏右键菜单中使用的NSMenuItems显示为灰色无法点击

问题描述

我正在尝试NSTextField用作NSMenuItem.

但它不起作用。

这是我的代码:

 class charPoolBoxForMenuItemInstance: NSTextField,NSTextFieldDelegate{
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.delegate = self
    }

    required init?(coder: NSCoder) {super.init(coder: NSCoder.init())}
   override func textDidChange(_ notification: Notification) {
   if self.currentEditor()?.selectedRange != nil{UserDefaults.standard.set(self.stringValue, forKey: "charPoolBox")

    }
  }
}

var  charPoolBoxForMenuItem = charPoolBoxForMenuItemInstance.init(string: String.init())

然后我将它添加到我的菜单中,如下所示:

let charPoolMenuItem = NSMenuItem()
    charPoolMenuItem.title = "Character Pool"
    charPoolMenuItem.view = charPoolBoxForMenuItem
    charPoolBoxForMenuItem.placeholderString = "Character Pool"
    charPoolBoxForMenuItem.frame = CGRect(x: 30, y: 0, width: 400, height: 22)
    menuBarMenu.addItem(charPoolMenuItem)

它看起来是灰色的:

在此处输入图像描述

更新 :

@objc func resetPoolChar(){charPoolBoxForMenuItem.stringValue = "abc"}


     let charPoolMenuItem = NSMenuItem()
    charPoolMenuItem.title = "Character Pool"
    charPoolMenuItem.view = charPoolBoxForMenuItem
    charPoolMenuItem.action = #selector(resetPoolChar)
    charPoolBoxForMenuItem.placeholderString = "Character Pool"
    charPoolBoxForMenuItem.frame = CGRect(x: 30, y: 0, width: 400,          height: 22)

标签: swiftmacoscocoa

解决方案


您还需要操作的目标:

   charPoolMenuItem.action = #selector(resetPoolChar)
   charPoolMenuItem.target = self

推荐阅读