gpt4 book ai didi

ios - 在AppDelegate中设置 View Controller 的变量

转载 作者:行者123 更新时间:2023-11-30 11:19:04 27 4
gpt4 key购买 nike

我试图在 View Controller 呈现时更改它的 ImageView 图像。 View Controller 出现在我的 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 中工作。任何帮助将不胜感激!

最佳答案

看看这个。尝试使用保护语句从 Storyboard实例化 viewController 并避免强制转换。

    guard let viewController = storyboard.instantiateViewController(withIdentifier: "myViewController") as? myViewController 
else { return false }
viewController.imageView?.image = UIImage(named: "myImage.png")

关于ios - 在AppDelegate中设置 View Controller 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51485810/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com