2016-11-17 79 views
4

Swift 3,Xcode 8.1。我想在UIViewController中顯示UIAlertControlleriOS。嘗試在其視圖不在窗口層次結構中的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

我調用該方法presentAlert在viewDidLoad

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

,並得到了警告:

警告:在試圖在UIViewController上呈現UIAlertController:0x7f904ac0d930:0x7f904ad08040其視圖不在窗口層次結構中!

如何避免該警告並顯示報警?

它起作用時,我試圖在初始ViewController中顯示警報,但它不起作用的另一個ViewController連接使用初始VC推push segue連接。

+0

你確定,那'rootViewController'上你想呈現'UIAlertController'是可見的,而不是覆蓋例如另一個模式視圖控制器? – dive

+0

在此viewController上按下調試視圖按鈕(它位於調試控制檯上的欄中)。在左側,你會看到你的整個視圖堆棧頂部的窗口。您可以右鍵單擊任何視圖以打印說明。將此與rootViewController()的視圖進行比較;必須證明您的rootViewController視圖不再處於層次結構中。選擇一個視圖並使用它。 –

+0

找到任何解決方案?遇到同樣的問題。 –

回答

16

在viewDidLoad中,您的應用程序並沒有出現在視圖控制器的用戶還,所以無法顯示一個警告。嘗試執行在viewDidAppear

+0

如果我在IBAction的按鈕 –

+1

@karnett中調用此方法的結果相同很好的答案。謝謝 –

3

代碼我有類似的問題/情況下動作片沒有在其上的另一個的ViewController被推一個的ViewController表示。它給出的錯誤也與你的錯誤類似。你所做的完美的工作在普通的ViewControllers上,但是不能在推送到其他ViewController上的ViewControllers上工作。

我通過使UIAlertController類的對象作爲我的類的實例變量,而不是將它保持本地觸發函數內部解決了這個問題。

所以你的情況,嘗試在其中instance變量的聲明之類的頂部聲明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) 
} 

可能是從一些bug蘋果方面在維護引起這個問題的參考。但是我上面寫的工作完美。

相關問題