【问题标题】:iOS. Attempt to present UIAlertController on UIViewController whose view is not in the window hierarchyIOS。尝试在视图不在窗口层次结构中的 UIViewController 上呈现 UIAlertController
【发布时间】:2017-04-01 15:27:47
【问题描述】:

Swift 3,Xcode 8.1。我想在UIViewController 中显示UIAlertController

我有方法:

private static func rootViewController() -> UIViewController {
    // cheating, I know

    return UIApplication.shared.keyWindow!.rootViewController!
}

static func presentAlert(_ message: String) {
    let alertView = UIAlertController(title: "RxExample", message: message, preferredStyle: .alert)
    alertView.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in })

    rootViewController().present(alertView, animated: true, completion: nil)
}

Full code of this class you can find here

我在viewDidLoad中调用了presentAlert方法:

override func viewDidLoad() {
    super.viewDidLoad()
    DefaultWireframe.presentAlert("test")
    ...
}

并收到警告:

警告:尝试在 UIViewController: 0x7f904ad08040 上呈现 UIAlertController: 0x7f904ac0d930,其视图不在窗口层次结构中!

如何避免警告并显示警报?

当我尝试在初始 ViewController 中显示 Alert 时它可以工作,但它在使用 push segue 与初始 VC 连接的另一个 ViewController 中不起作用。

【问题讨论】:

  • 您确定您尝试在其上显示UIAlertControllerrootViewController 是可见的,并且不会被另一个模态视图控制器覆盖吗?
  • 在这个 viewController 上按下调试视图按钮(它在调试控制台上方的栏中)。在左侧,您将看到整个视图堆栈,窗口位于顶部。您可以右键单击任何视图以打印说明。将此与 rootViewController() 的视图进行比较;它必须显示您的 rootViewController 的视图如何不再在层次结构中。选择一个视图并使用它。
  • 找到任何解决方案了吗?遇到同样的问题。

标签: ios swift uiviewcontroller


【解决方案1】:

在 viewDidLoad 中,您的应用尚未向用户呈现视图控制器,因此无法显示警报。尝试在 viewDidAppear 中执行该代码

【讨论】:

  • 如果我在按钮的IBAction中调用这个方法也是一样的结果
  • @karnett 很好的答案。谢谢
【解决方案2】:

我有类似的问题/情况,操作表没有显示在另一个 ViewController 上的 ViewController 上。它给出的错误也与您的相似。您所做的工作在普通 ViewController 上完美运行,但不适用于在其他 ViewController 上推送的 ViewController。

我通过将 UIAlertController 类的对象作为我的类的实例变量而不是在触发函数中将其保持在本地来解决了这个问题。

因此,在您的情况下,请尝试在声明实例变量的类顶部声明 var alertView: UIAlertController?,然后在所需的触发函数中对其进行初始化,以便像这样使用它:

static func presentAlert(_ message: String) {
    self.alertView = UIAlertController(title: "RxExample", message: message, preferredStyle: .alert)
    alertView.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in })

    rootViewController().present(alertView, animated: true, completion: nil)
}

可能是 Apple 在维护导致此问题的参考方面的一些错误。但是我在上面写的解决方法很完美。

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 2012-08-05
    • 2023-03-31
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多