在AppDelegate中设置视图控制器的变量

时间:2018-07-23 19:18:56

标签: ios swift

我试图在显示时更改视图控制器的ImageView图像。我的AppDelegate文件中显示了视图控制器。但是,无论何时触发逻辑,应用程序都会崩溃(lldb),并且错误显示为:“线程1:在展开可选值时意外发现nil”。我可以使用默认配置推送ViewController,但是从AppDelegate显示它们时,我无法编辑它们的变量。我在AppDelegate中的代码如下:

//the viewController to present
let viewController = storyboard.instantiateViewController(withIdentifier: "myViewController") as! myViewController
viewController.imageView.image = UIImage(named: "myImage.png")

// navigationController is my instantiated navigation controller in my storyboard
navigationController.pushViewController(viewController, animated: true)

我还做了一个自己的pushViewController扩展,可以容纳完成处理程序:

navigationController.pushViewController(viewController, animated: true, completion: {
                viewController.imageView.image = UIImage(named: "myImage.png")
            })

不幸的是,这仍然没有奏效。当我在非AppDelegate的其他文件中执行此操作时,它工作正常。由于某种原因,我无法在AppDelegate中使用它。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

检查一下。在从情节提要中实例化viewController时,请尝试使用Guard语句,并避免强制转换。

users