【问题标题】:Setting variables of view controller in AppDelegate在 AppDelegate 中设置视图控制器的变量
【发布时间】:2018-12-31 07:40:39
【问题描述】:

我正在尝试在显示视图控制器时更改其 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 中工作。任何帮助将不胜感激!

【问题讨论】:

  • 一个非常常见的错误。在视图控制器被实例化的那一刻,出口还没有连接。使用属性传递图像并将图像分配给viewDidLoadmyViewController 中的图像视图。并且根据命名约定,类名以大写字母开头。

标签: ios swift


【解决方案1】:

看看这个。尝试在 storyboard 中实例化 viewController 时使用 guard 语句,避免强制转换。

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

【讨论】:

  • 不幸的是,这不起作用,但我设法弄清楚了。我会尽快用我的答案更新这篇文章。
猜你喜欢
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 2017-04-11
相关资源
最近更新 更多