简体   繁体   中英

NSMennuItems used in menubar right click menu appear grayed out and cant be clicked

I am trying to use NSTextField as a NSMenuItem .

But it's not working.

Here is my code:

 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())

Then I add it to my menu like so:

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)

And here's how it looks greyed out:

在此处输入图片说明

update :

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

You also need the target for the action:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM