2017-07-25 41 views
1
視圖控制器我使用使用此代碼,我從什麼地方找到的堆棧溢出移動從應用程序委託一個新的視圖控制器

斯威夫特應用程序崩潰移動從AppDelegate中

func changeRootViewController(with identifier:String!) { 
    let storyboard = self.window?.rootViewController?.storyboard 
    let desiredViewController = storyboard?.instantiateViewController(withIdentifier: identifier); 

    let snapshot:UIView = (self.window?.snapshotView(afterScreenUpdates: true))! 
    desiredViewController?.view.addSubview(snapshot); 

    self.window?.rootViewController = desiredViewController; 

    UIView.animate(withDuration: 0.3, animations: {() in 
     snapshot.layer.opacity = 0; 
     snapshot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5); 
    }, completion: { 
     (value: Bool) in 
     snapshot.removeFromSuperview(); 
    }); 
} 

它工作正常,我能移動到具有動畫的新視圖控制器(要求,要求爲)。但是,只要我移動到其他應用程序並返回,該應用程序就會崩潰並出現錯誤。

Cannot snapshot view (; layer = >) with afterScreenUpdates:NO, because the view is not in a window. Use afterScreenUpdates:YES. fatal error: unexpectedly found nil while unwrapping an Optional value

其他的代碼,我從AppDelegate中

打開視圖控制器
func showViewController(id: String){ 
    let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
    let initialViewControlleripad : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: id) as UIViewController 
    self.window = UIWindow(frame: UIScreen.main.bounds) 
    self.window?.rootViewController = initialViewControlleripad 
    self.window?.makeKeyAndVisible() 
} 

它完美,但嘗試添加動畫時的動畫效果不起作用。所以善意幫助解決這些問題。

+3

不要誤會我這裏一個好的學習是「不要只是從StackOverflow複製代碼」 - 而是嘗試理解它並由您自己實現。我之前也犯過同樣的錯誤。 它崩潰的原因是您正在拍攝當前窗口的快照並將其用於動畫。當你從後臺打開應用程序'self.window'可能是零,所以你實際上不能從中獲取快照。我會建議找到一種不同的方式來添加您的動畫時,打開應用程序 – Bluewings

+0

https://www.gitbook.com/book/tra38/essential-copying-and-pasting-from-stack-overflow/details –

+0

只是檢查值需要在desiredViewController存在,當你從appdelgate到達? –

回答

0

你試過動畫嗎?

UIView.transition(with: appDel.window!, 
       duration: 0.25, 
       options: .transitionCrossDissolve, 
      animations: { appDel.window?.rootViewController = vc } , 
      completion: nil)