【问题标题】:NSPopUpButton - Weird behavior when populating dynamic content with Cocoa BindingNSPopUpButton - 使用 Cocoa Binding 填充动态内容时的奇怪行为
【发布时间】: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 绑定。我的NSPopUpButtonContent Values 绑定到属性contentsSelected Index 绑定到selectedIndex。我将ViewController 对象设置为NSPopUpButton 的嵌入NSMenu 的代表。

所以,NSPopUpButton 的内容没有问题,但是它会检查我在NSPopUpButton 中选择的任何项目,即使我选择了其他内容,它也会检查它们,最终它会变成这样:

而且,如果我打开菜单 (NSPopUpButton) 并通过不选择菜单中的任何项目(单击菜单以外的任何位置)直接关闭它,它会自动选择第一项(“无”)而不管之前选择的项目。

然后,我决定在关闭菜单后通过实现menuDidClose(_:) 来监控selectedIndex 的值,结果selectedIndex 正是我之前选择的(这是正确的)。 即使我删除了对 selectedIndex 的绑定,此问题仍然存在。

这真的很奇怪,没有任何意义。谁能解释这是怎么回事?我怎样才能正确地使用静态和动态内容的混合填充NSPopUpButton

【问题讨论】:

    标签: swift cocoa cocoa-bindings nspopupbutton


    【解决方案1】:

    问题是由menu.items[index] = .separator() 引起的。它替换了菜单的 item 数组。弹出按钮的itemArray属性指向菜单的item数组,该属性不做调整。弹出按钮找不到关闭复选标记的菜单项。将菜单项替换为

    menu.removeItem(at: index)
    menu.insertItem(NSMenuItem.separator(), at: index)
    

    或者在IB的菜单中放一个分隔项,使用绑定的Content Placement Tag设置,在分隔项下面插入绑定项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      相关资源
      最近更新 更多