Swift: Why does "Pop Up Button" throw NSInternalInconsistencyException?

2.4k Views Asked by At

I created a "Pop Up Button" following the WWDC video here:

"Build interfaces with style" https://developer.apple.com/videos/play/wwdc2021/10196/?time=602

After adding the pop up button like shown in the video, I created an IBAction function like this:

@IBAction func onLanguageSelected(_ sender: Any?) {
    print("menu selection updated!")
}

Then, I hook up the two menu items to this IBAction function like this:

enter image description here

Build was successful, at runtime, upon click on the button, the app crashed, and throws the following exception:

Assertion failure in -[UIMenu establishInitialDefaultSingleSelection], UIMenu.m:535 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Menu does not have a valid element for default selection'

Why do I this exception? What needs to be fixed here?

3

There are 3 best solutions below

1
petermichael On

You need to add menu items to the Pop Up Button like:

@IBOutlet weak var popUpButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    setupPopUpButton()
}

func setupPopUpButton() {
    let popUpButtonClosure = { (action: UIAction) in
        print("Pop-up action")
    }
            
    popUpButton.menu = UIMenu(children: [
        UIAction(title: "First Entry", handler: popUpButtonClosure),
        UIAction(title: "Second Entry", handler: popUpButtonClosure)
    ])
    popUpButton.showsMenuAsPrimaryAction = true
}
1
Weston Mitchell On

All menu items must be connected to an @IBAction and the Pop Up Button must have the following config items selected in the Attributes Inspector:

Selection as Primary Action

Shows as Primary Action

2
bauerMusic On
  1. Create an action in code:
@IBAction func menuAction(_ sender: Any) {
    
}
  1. Drag each menu to the First Responder:

enter image description here

  1. Select your action

enter image description here

  1. Repeat for each action (no option currently to add tag to menu item)