我希望在app启动时在AppDelegate中的rootViewController上显示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
}
警报未出现在rootViewController上。请帮帮我。
答案 0 :(得分:2)
原因是视图尚未加载,如果您查看控制台,您可能会发现这样的日志:
警告:尝试出现'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)
}