简体   繁体   中英

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

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:

在此处输入图像描述

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM