【问题标题】:NSMenuItem setting state not workingNSMenuItem 设置状态不起作用
【发布时间】:2016-02-01 04:51:27
【问题描述】:

我在 Swift 1.2 中有一个基于文档的应用程序。我想以编程方式生成对当前 NSDocument 有操作的NSMenuItem,然后检查该选择。到目前为止,这是我所拥有的:

AppDelegate

// generate items
for thing in thingArray {
    var newThing = NSMenuItem(title:name, action: Selector("myMethod:"), keyEquivalent: "")
    newThing.enabled = true
    submenu.addItem(newThing)
}

我的文档

// getting current AppDelegate
let app = NSApplication.sharedApplication().delegate as! AppDelegate

// called by user selected menu item
@IBAction func myMethod(sender: NSMenuItem) {
    let parent = sender.parentItem!

    // iterate through all Items to setState: NSOffState

    for item in parent.submenu!.itemArray as! [NSMenuItem] {
        if workspace?.name == item.title {
            item.state = NSOnState     
            break
        }
    }
}

我知道直到item.state 的所有代码都在工作。我放了打印日志来测试它。但是发生的情况通常是菜单项没有被检查,但偶尔会。

我最好的猜测是菜单没有令人耳目一新,但我不知道该怎么做。难道NSMenuItem的动作也是通过First Responder链发送的?任何帮助将不胜感激。

【问题讨论】:

  • 一个更有效的方法是创建一个实例变量currentIndex 保存当前菜单项的索引。调用myMethod函数时,将currentIndex的菜单项状态设置为NSOffState,将sender的状态设置为NSOnState。然后将currentIndex 设置为sender 的索引。这样可以避免重复循环。
  • 在哪里取消选中菜单项?
  • @vadian 这是个好主意(无论如何我都会这样做),但我得到了同样的行为。
  • @Willeke 我在发布的代码中省略了它,但我会编辑我的原始帖子以显示何时这样做。

标签: swift macos cocoa nsmenuitem


【解决方案1】:

好的...我明白发生了什么。 AppDelegate 中创建菜单项的部分每 3 秒调用一次(我正在使用的 API 的一部分)。问题是菜单项正在重新创建,所以我设置的状态并不总是菜单中当前的NSMenuItem

我发现我可以在 NSDocument 中使用validateMenuItem 来更新每个符合我的条件的菜单项。

override func validateMenuItem(menuItem: NSMenuItem) -> Bool {
    menuItem.state = workspaceIndex == menuItem.tag ? NSOnState : NSOffState
    return true
}

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多