我想在应用程序启动时在 AppDelegate 中的根视图控制器上显示 alertViewController。 这里有一段代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
return true
}
警报未出现在根视图控制器上。请帮助我。
原因是视图尚未加载,如果您查看控制台,您可能会发现这样的日志:
警告:尝试在视图不在窗口层次结构中的"swiftHere.ViewController: 0x7ff289007740"上显示!
您可以调度它,直到 rootViewController 加载:
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let alert: UIAlertController = UIAlertController(title: "This is title", message: "This is message.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}