【问题标题】:Can't present alertViewController on rootViewController in AppDelegate无法在 AppDelegate 中的 rootViewController 上显示 alertViewController
【发布时间】:2018-06-18 14:01:50
【问题描述】:

我想在应用启动时在 AppDelegate 中的 rootViewController 上显示 alertViewController。这里sn-p的代码:

 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 上。请帮帮我。

【问题讨论】:

  • window 有值还是 nil? rootViewController 的同样问题。
  • 检查windowLevel并使其等于UIWindowLevelAlert
  • window 和 rootViewController 不为零。

标签: ios swift appdelegate uialertviewcontroller


【解决方案1】:

原因是视图还没有加载,如果你查看控制台你可能会发现这样的日志:

警告:尝试在“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)

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2012-11-05
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多