1

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.)

Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • See [Pull-Down Buttons](https://developer.apple.com/design/human-interface-guidelines/macos/buttons/pull-down-buttons/). "If you need to provide a list of mutually exclusive choices that aren’t commands, use a pop-up button instead." – Willeke Aug 11 '19 at 22:42

1 Answers1

2

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.

red_menace
  • 3,162
  • 2
  • 10
  • 18
  • If index starts at 1 when a developer adds an item it should add first item at 1 not at 0. – Frankenstein Aug 11 '19 at 21:36
  • You would need to take that up with Apple, it works the way they wrote it. I usually just set the first array item to the title, and add menu items from there. If I need the title to change, I reset the title of the pull-down with the selection (or use a popup button). – red_menace Aug 11 '19 at 22:31