这是因为alertController是基于当前视图控制器的,如果在一个页面(如控制器A)上初始化了一个alertController,然后在另一个页面(如控制器B)上尝试使用同一个alertController实例,那么它将只显示在控制器A上。
因此,可以在每个需要显示的页面上单独创建和显示alertController,或者将alertController设置为全局变量并且只在需要时初始化,这种方法可以保证alertController可以在任何一个页面上显示。
示例代码:
方法一:在每个需要显示的页面上创建和显示alertController
在控制器A中:
let alertController = UIAlertController(title: "提示", message: "你确定要删除吗?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "确定", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
在控制器B中:
let alertController = UIAlertController(title: "提示", message: "你确定要退出登录吗?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "确定", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
方法二:将alertController设置为全局变量并只在需要时初始化
在AppDelegate.swift文件中定义全局变量:
var alertController: UIAlertController?
在需要显示alertController的控制器中:
if alertController == nil {
alertController = UIAlertController(title: "提示", message: "你确定要删除吗?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "确定", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "