Buggy NSPopupButton in Cocoa MacOS Swift/Objective-C doesn't allow user to select first item

377 Views Asked by At

If we tried to create an NSPopupButton in swift/objective-c we find that if we don't set pullsdown to false, once an item other than the 1st item is selected you would never be able to select the first item back.

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")
    }
}

Is there a way where I could fix this? (Note: I don't want answers that say to set pullsDown to false and issue is fixed. I need to keep the behaviour of the PopupButton as expected.)

1

There are 1 best solutions below

2
red_menace On

From the Documentation archive, that is the way a pull-down button works. It is more like a menu - the title isn’t based on the selection, the title only changes when you explicitly set it. The list actually starts at index 1 - index 0 can be used for storing the title (although you should still set it), which is why the first item in your list isn’t being used in the menu.