Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/109.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 网间网操作系统。尝试在视图不在窗口层次结构中的UIViewController上显示UIAlertController_Ios_Swift_Uiviewcontroller - Fatal编程技术网

Ios 网间网操作系统。尝试在视图不在窗口层次结构中的UIViewController上显示UIAlertController

Ios 网间网操作系统。尝试在视图不在窗口层次结构中的UIViewController上显示UIAlertController,ios,swift,uiviewcontroller,Ios,Swift,Uiviewcontroller,Swift 3,Xcode 8.1。我想在UIViewController中显示UIAlertController 我有一些方法: private static func rootViewController() -> UIViewController { // cheating, I know return UIApplication.shared.keyWindow!.rootViewController! } static func presentAlert(_

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)
}

我在
viewDidLoad
中调用presentAlert方法:

override func viewDidLoad() {
    super.viewDidLoad()
    DefaultWireframe.presentAlert("test")
    ...
}
并得到警告:

警告:试图在视图不在窗口层次结构中的UIViewController:0x7f904ad08040上显示UIAlertController:0x7f904ac0d930

如何避免警告并显示警告


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

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

我遇到了类似的问题/情况,即操作表没有显示在另一个ViewController上的ViewController上。它给出的错误也与您的类似。您所做的工作在普通的ViewController上非常有效,但在推到其他ViewController上的ViewController上却不起作用

我通过将class
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)
}

可能是苹果方面在维护引用方面的一些错误导致了这个问题。但是我上面写的变通方法非常有效。

如果我在的iAction中调用这个方法,结果也是一样的button@karnett回答得很好。感谢您确定,您试图显示的
UIAlertController
上的
rootViewController
是可见的,并且没有被另一个模态视图控制器覆盖,例如?按下此viewController上的调试视图按钮(位于调试控制台上方的栏中)。在左侧,您将看到整个视图堆栈,窗口位于顶部。您可以右键单击任何视图以打印说明。将其与rootViewController()的视图进行比较;必须在这种情况下显示rootViewController的视图如何不再位于层次结构中。选择一个可用的视图并使用它。找到解决方案了吗?遇到同样的问题。