How to have an initial state with no option selected with UIButton (popup/pulldown button)?

216 Views Asked by At

I have this particular code

let genderOptions = ["Male".localized, "Female".localized]
    .map { UIAction(title: $0, state: .off, handler: {_ in }) }
genderButton.changesSelectionAsPrimaryAction = true
genderButton.menu = UIMenu(children: genderOptions)

enter image description here

I have set all the UIAction's state to .off, but still it is selecting the first item by default. Below is the Apple's documentation.

enter image description here

But when I print the selectedElements, it prints the following:

print(genderButton.menu?.selectedElements)

enter image description here even though all the UIAction items state = .off, it prints an array with the first item as selected.

Q: How to have an initial state without any selection? Is popup button a good option to use here or should I use UITextField with UIPickerView? If anyone could give a complete solution, it would be great.

1

There are 1 best solutions below

0
On

Assuming you have set changesSelectionAsPrimaryAction = true, you can add a hidden (with the .hidden attribute) action as the first action:

var genderOptions = [UIAction(title: "Select Gender", attributes: [.hidden], handler: {_ in })]
genderOptions.append(contentsOf: ["Male", "Female"]
    .map { UIAction(title: $0, handler: {_ in }) })

The button selects the first action and uses its title as the button's title. The user can then select one of the other two actions. But they cannot select the hidden action.

The .disabled attribute also prevents the user from selecting the action, but the option is still visible.

See also: UIMenuElement.Attributes