如何使用Swift 1.2 / Cocoa以编程方式在NSToolbar上选择NSToolbarItem

时间:2015-08-03 17:06:01

标签: macos swift cocoa nstoolbar nstoolbaritem

我正在使用最新的XCode 6.4和Swift 1.2。 我正在尝试以编程方式在我的NSToolbar中选择NSToolbarItem。我在互联网上搜索了很多,应该有一个名为setSelectedItemIdentifier的NSToolbar方法,但该方法不会exist(不再是?)。

还有另一种方法可以实现这一目标吗? 也许是这样的事情:

NSApplication.sharedApplication().sendAction(Selector("click"), to: myNSToolbarItem, from: sender)

但我不知道应该使用什么而不是“点击”。 提前谢谢!

Neo回复后更新: 我希望toolbaritem在视觉上“选中”,这会改变它的颜色。我知道如何调用func,但这不会改变toolbaritem的“选定”状态。所以,如果我可以模拟鼠标点击nstoolbaritem,这将解决我的问题(或者更换NSToolbar.setSelectedItemIdentifier)。

2 个答案:

答案 0 :(得分:0)

你的ToolbarItem是否与你的ViewController中的func连接......你唯一需要做的就是像调用任何其他函数一样调用func,或者有什么特别的东西?

你能再给我一些代码吗?

答案 1 :(得分:0)

selectedItemIdentifier现在是NSToolbar上的可设置属性,可用于代替setSelectedItemIdentifier。确保NSToolbarItem是可选的(如果使用Interface Builder,默认情况下禁用),并且您已为工具栏项设置标识符(或使用NSToolbarItem的itemIdentifier)。

然后,只需将selectedItemIdentifier设置为有效的工具栏项标识符即可。如果没有故事板实现:

//Create the toolbar item and set an identifier
let demoToolBarItem = NSToolbarItem(itemIdentifier: "account")

//Set the NSToolbarDelegate
preferencesToolbar.delegate = self

//Implement toolbarSelectableItemIdentifiers(NSToolbar)
func toolbarSelectableItemIdentifiers(NSToolbar) -> [String]{
  return ["account"]
}

//Set the selected item on the toolbar
preferencesToolbar.selectedItemIdentifier = "account"