【发布时间】:2019-10-04 08:51:02
【问题描述】:
我正在尝试创建一个具有动态内容的 NSPopUpButton,这是我的设计:
+-------------+
| None | <-- Static
| Last Item | <-- Static
|-------------| <-- Separator
| History: | <-- Dynamic: "History:" / "No History"
| ... | <-- Dynamic
+-------------+
这是我的 ViewController.swift 代码:
class ViewController: NSViewController, NSMenuDelegate {
@objc dynamic var contents: [String] = ["None", "Last Item", ""]
@objc dynamic var selectedIndex: Int = 0
func updateContent() {
// update contents array
}
override func viewDidLoad() {
super.viewDidLoad()
updateContent()
// other code
}
func menuNeedsUpdate(_ menu: NSMenu) {
for (index, item) in menu.items.enumerated() {
if item.title == "" {
menu.items[index] = .separator()
} else if item.title == "History:" || item.title == "No History" {
menu.items[index].isEnabled = false
}
}
}
func menuDidClose(_ menu: NSMenu) {
print(selectedIndex)
}
}
我使用界面构建器进行了 Cocoa 绑定。我的NSPopUpButton 的Content Values 绑定到属性contents,Selected Index 绑定到selectedIndex。我将ViewController 对象设置为NSPopUpButton 的嵌入NSMenu 的代表。
所以,NSPopUpButton 的内容没有问题,但是它会检查我在NSPopUpButton 中选择的任何项目,即使我选择了其他内容,它也会检查它们,最终它会变成这样:
而且,如果我打开菜单 (NSPopUpButton) 并通过不选择菜单中的任何项目(单击菜单以外的任何位置)直接关闭它,它会自动选择第一项(“无”)而不管之前选择的项目。
然后,我决定在关闭菜单后通过实现menuDidClose(_:) 来监控selectedIndex 的值,结果selectedIndex 正是我之前选择的(这是正确的)。 即使我删除了对 selectedIndex 的绑定,此问题仍然存在。
这真的很奇怪,没有任何意义。谁能解释这是怎么回事?我怎样才能正确地使用静态和动态内容的混合填充NSPopUpButton?
【问题讨论】:
标签: swift cocoa cocoa-bindings nspopupbutton