简体   繁体   English

Swift:为什么“弹出按钮”抛出 NSInternalInconsistencyException?

[英]Swift: Why does "Pop Up Button" throw NSInternalInconsistencyException?

I created a "Pop Up Button" following the WWDC video here:我在此处的 WWDC 视频之后创建了一个“弹出按钮”:

"Build interfaces with style" https://developer.apple.com/videos/play/wwdc2021/10196/?time=602 “用风格构建界面” 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 函数,如下所示:

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

Then, I hook up the two menu items to this IBAction function like this:然后,我将两个菜单项连接到这个 IBAction 函数,如下所示:

在此处输入图像描述

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' -[UIMenu establishInitialDefaultSingleSelection] 中的断言失败,UIMenu.m:535 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“菜单没有用于默认选择的有效元素”

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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