2016-10-28 81 views
1

我在AppDelegate中使用以下代碼在應用程序中顯示彈出窗口,當選擇按鈕時,我最終會將其移至標籤超鏈接,但僅測試當前。嘗試呈現*其視圖不在窗口層次結構中

let storyboard = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("test") as! ViewController 
    let popOverVC = UIStoryboard(name:"Main", bundle: nil).instantiateViewControllerWithIdentifier("sbPopUpID") as! PopUpViewController 
    storyboard.addChildViewController(popOverVC) 
    popOverVC.view.frame = storyboard.view.frame 
    storyboard.view.addSubview(popOverVC.view) 
    popOverVC.didMoveToParentViewController(storyboard) 
    self.window?.rootViewController?.presentViewController(storyboard, animated: true, completion: nil) 

我第一次選擇按鈕,此正常工作,但是在隨後的所有按鈕,按以下錯誤顯示。

2016-10-28 11:27:40.551 testfordeeplinks[20496:104536] Warning: Attempt to present on whose view is not in the window hierarchy!

回答

0

rootViewController並不一定是指當前可見的視圖控制器。例如,如果您使用UINavigationController,rootViewController將持有對該導航控制器的引用,該引導控制器本身被深埋在視圖層次結構中,因此當您嘗試在其上呈現視圖控制器時會出現錯誤。我會推薦做的是抓住navController.viewControllers中的最後一個視圖控制器並在其上顯示彈出窗口。請參閱以下代碼:

let appDel = UIApplication.sharedApplication().delegate as! AppDelegate 
if let navController = appDel.keyWindow?.rootViewController as? UINavigationController { 
    if let visibleVC = navController.viewControllers.last { 
     visibleVC.presentViewController(storyboard, animated: true, completion: nil) 
    } 
} 

試試看,讓我知道。 :)

+0

感謝雅各,將返回以下錯誤:從「UIViewController的」 低迷現狀,只有解開自選,你的意思是使用「!」? – ScoopMatt

+0

我沒有看到錯誤,所以我猜你只是忘了粘貼它? :P –

+0

來自「UIViewController」的下變量只能解開可選項,是不是要使用'!'? – ScoopMatt

3

對於任何人在未來絆倒這一點,這是我如何解決;

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    appDelegate.window?.rootViewController = storyboard 
相關問題