0

我想在启动应用程序时在 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 上。请帮我。

4

1 回答 1

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)

    }
于 2018-01-09T14:09:20.383 回答