首页 > 解决方案 > Cocoa MacOS Swift/Objective-C 中的 Buggy NSPopupButton 不允许用户选择第一项

问题描述

如果我们尝试NSPopupButton在 swift/objective-c 中创建一个,我们会发现如果我们不将 pullsdown 设置为 false,一旦选择了第一个项目以外的项目,您将永远无法选择第一个项目。

class PopupButton: NSPopUpButton {

    let items = ["item 1", "item 2", "item 3"]

    override init(frame buttonFrame: NSRect, pullsDown flag: Bool) {
        super.init(frame: buttonFrame, pullsDown: flag)

        items.forEach { item in
            menu?.addItem(withTitle: item, action: #selector(handleSelectedItem(_:)), keyEquivalent: "")
        }
    }

    @objc private func handleSelectedItem(_ selectedItem: NSMenuItem) {
        title = selectedItem.title
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

有没有办法可以解决这个问题?(注意:我不希望将 pullsDown 设置为 false 并且问题已修复的答案。我需要保持 PopupButton 的行为符合预期。)

标签: swiftcocoanspopupbutton

解决方案


文档存档中,这是下拉按钮的工作方式。它更像是一个菜单 - 标题不基于选择,标题仅在您明确设置时才会更改。列表实际上从索引 1 开始 - 索引 0 可用于存储标题(尽管您仍应设置它),这就是为什么列表中的第一项未在菜单中使用的原因。


推荐阅读