【发布时间】: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