点击UIAlertAction后,如何通过UINavigationController跳转新ViewController
要实现点击弹窗按钮后跳转页面,核心是在对应按钮的回调闭包里,利用当前控制器的navigationController执行页面入栈操作。前提是当前ViewController必须已经被嵌入到UINavigationController中,否则navigationController会为nil,无法执行push操作。
以下是修改后的完整代码:
func showAlert() { let alert = UIAlertController(title: "选择", message: "请选择你想要查看的统计类型", preferredStyle: .alert) // 团队统计按钮回调:跳转TeamStatsViewController alert.addAction(UIAlertAction(title: "团队统计", style: .default, handler: { action in // 初始化目标ViewController(替换为你实际创建的类名) let teamStatsVC = TeamStatsViewController() // 通过导航控制器push页面 self.navigationController?.pushViewController(teamStatsVC, animated: true) })) // 球员统计按钮回调:跳转PlayerStatsViewController alert.addAction(UIAlertAction(title: "球员统计", style: .default, handler: { action in let playerStatsVC = PlayerStatsViewController() self.navigationController?.pushViewController(playerStatsVC, animated: true) })) // 取消按钮回调 alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { action in print("点击了取消") })) present(alert, animated: true) }
关键补充说明:
- 如果目标ViewController是通过Storyboard创建的,需要改用Storyboard初始化方式,示例:
let teamStatsVC = self.storyboard?.instantiateViewController(withIdentifier: "TeamStatsVC") as! TeamStatsViewController - 若当前ViewController不在导航栈中,需先将其嵌入UINavigationController(可在Storyboard中设置,或代码里用
UINavigationController(rootViewController: 当前VC)),再执行push操作。
内容的提问来源于stack exchange,提问作者Coder44
相关产品推荐
相关产品推荐

