Swift中UIAlertController点击No按钮无法关闭并返回SecondViewController问题
UIAlertController "No"按钮无法关闭弹窗的解决方案
核心问题分析
你遇到的问题大概率是弹窗关闭逻辑错误或者循环引用导致控制器无法响应dismiss操作,以下是针对性的解决步骤:
正确的弹窗实现代码
在你的GameViewController中,按以下方式重构弹窗逻辑:
func showResetConfirmationAlert() { let alert = UIAlertController(title: "重置游戏", message: "确定要重置当前游戏进度吗?", preferredStyle: .alert) // Yes按钮 - 重置游戏并关闭弹窗 let yesAction = UIAlertAction(title: "Yes", style: .default) { [weak self] _ in self?.resetGame() // 执行你的游戏重置逻辑 self?.dismiss(animated: true) // 关闭弹窗 } // No按钮 - 关闭弹窗并返回SecondViewController let noAction = UIAlertAction(title: "No", style: .cancel) { [weak self] _ in // 先关闭弹窗,在完成回调里处理返回逻辑 self?.dismiss(animated: true) { // 根据你跳转GameViewController的方式选择对应代码: // 1. 如果是通过UINavigationController push过来的: self?.navigationController?.popViewController(animated: true) // 2. 如果是通过present方式打开的GameViewController: // self?.dismiss(animated: true) } } alert.addAction(yesAction) alert.addAction(noAction) present(alert, animated: true) }
关键注意事项
- 避免循环引用:必须在闭包中使用
[weak self],否则弹窗的闭包会强引用GameViewController,导致控制器无法响应dismiss指令 - 正确调用dismiss:不要直接调用
myAlertController?.dismiss,应该由present弹窗的控制器(也就是GameViewController自身,即self)来调用dismiss,这样才能正确关闭当前弹出的alert - 区分跳转方式:返回
SecondViewController时,要根据你打开GameViewController的方式选择popViewController(push场景)或dismiss(present场景)
额外排查点
如果以上代码还是无效,检查以下内容:
- 确认
GameViewController的modalPresentationStyle没有设置为特殊值(比如.fullScreen以外的样式可能会有兼容问题,但alert一般不受影响) - 检查是否有其他代码在弹窗显示后,拦截了控制器的
dismiss操作(比如自定义的navigationController代理逻辑)
内容的提问来源于stack exchange,提问作者AranAli
相关产品推荐
相关产品推荐

