ios - 从 AppDelegate 移动到 View Controller 后 Swift App 崩溃

标签 ios iphone swift xcode

我正在使用我从堆栈溢出的某个地方找到的这段代码从应用程序委托(delegate)移动到一个新的 View Controller

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

它工作正常,我可以移动到带有动画的新 View Controller (WHICH IS REQUIRED)。但是,一旦我转到其他某个应用并返回,该应用就会因错误而崩溃。

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 打开 View Controller 的其他代码

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

它工作得很好,但是当尝试添加动画时,动画不起作用。请帮助解决这些问题。

最佳答案

你试过像这样的动画吗?

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

关于ios - 从 AppDelegate 移动到 View Controller 后 Swift App 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293749/

相关文章:

ios - 网络蓝牙在移动设备中的可用程度如何?

ios - 顺利停止 CABasicAnimation

iphone - NSMutableArrays 没有将它们的对象保存在共享实例中

iphone - 触摸时UISearchBar崩溃

ios - IOS/Swift 中的自定义键盘语音到文本问题

ios - 如何收到用户使用 ShareKit 分享内容的通知?

jQuery $.live() 不适用于 iPhone 上的表格行

iphone - 发送 qLaunchSuccess 数据包失败

ios - sqlite3_prepare_v2 返回 1

ios - 通过 UIImagepickerController 快速获取元数据