我在 WWDC 视频之后创建了一个“弹出按钮”:
https://developer.apple.com/videos/play/wwdc2021/10196/?time=602
添加如视频中所示的弹出按钮后,我创建了一个如下所示的 IBAction 函数:
@IBAction func onLanguageSelected(_ sender: Any?) {
print("menu selection updated!")
}
然后,我将两个菜单项连接到此 IBAction 函数,如下所示:
构建成功,在运行时,单击按钮后,应用程序崩溃,并抛出以下异常:
-[UIMenu setInitialDefaultSingleSelection] 中断言失败,UIMenu.m:535 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“菜单没有用于默认选择的有效元素”
为什么我会出现这种异常?这里需要修复什么?
您需要向弹出按钮添加菜单项,例如:
@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
}
所有菜单项必须连接到
@IBAction
并且 Pop Up Button
必须在属性检查器中选择以下配置项:
Selection as Primary Action
Shows as Primary Action