【问题标题】:Swift4 - Unexpectedly found nil - Setting Image to Button [duplicate]Swift4 - 意外发现 nil - 将图像设置为按钮 [重复]
【发布时间】:2019-03-12 07:24:58
【问题描述】:

大家好,我想创建一个帮助类,它将我所有的图片设置到我的按钮上。但总是图片为零:(我的错误在哪里?

1 级(动作发生的地方)

class RandomClass {
    let imageSetter = ImageSetter()
    let mvc = MainViewController()

    func actionWhenConnected(){
    imageSetter.setButtonImages(nameOfButton: mvc.ConnectingButtonLabel, nameOfImage: "Connection/ConnectionOn", nameOfColor: .green, forStatus: .normal)
    }
}

这意味着当函数被调用时,我的 MainViewController 中的图像应该切换到我的绿色 Connection On Picture

2 类(助手类)

class ImageSetter{

func setButtonImages(nameOfButton:UIButton, nameOfImage:String, nameOfColor:UIColor, forStatus:UIControl.State){
    nameOfButton.setImage(UIImage(named: nameOfImage), for: forStatus)
    let origImage = UIImage(named: nameOfImage)
    let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
    nameOfButton.setImage(tintedImage, for: .normal)
    nameOfButton.tintColor = nameOfColor
    }

}

Assets

在我的 MainViewController 中它可以工作:( 好像RandomClass没找到assets.xcassets是因为找不到图片的名字?

解决了!

    func actionWhenConnected(){
    let mvc = UIApplication.shared.keyWindow?.rootViewController as! MainViewController
    imageSetter.setButtonImages(nameOfButton:mvc.ConnectingButtonLabel, nameOfImage: "Connection/ConnectionOff", nameOfColor: .red, forStatus: .normal)
}

非常感谢@matt

【问题讨论】:

  • 如果你把ConnectionOn而不是Connection/ConnectionOn作为图像名称呢?
  • 是的,现在添加了资产的屏幕截图。编辑:截图 ConnectionOff 但同样的问题

标签: swift image button


【解决方案1】:

问题出在这一行:

let mvc = MainViewController()

想想短语MainViewController() 的作用!它创建 MainViewController 的一个新的单独的第二个实例。因此,视图永远不会从情节提要加载,按钮的出口永远不会连接,并且您会崩溃。

您想要的是对实际 MainViewController 实例的引用,该实例的视图已经存在于您的界面中。那就是您可以看到的带有按钮的那个。

在我的 MainViewController 中它可以工作

是的,因为在 MainViewController 中您知道如何获取对此实例的引用 — 您只需说 self。但即使在那里,如果你说MainViewController(),它也行不通。

好像 RandomClass 无法访问 assets.xcassets 因为它没有找到图像的名称?

是的。它找到图像。 nil 是 按钮

【讨论】:

  • 好的,我明白这个问题,但我不知道如何解决这个问题。看过其他帖子,但我无法找到工作参考。你能给我一个提示吗?我当然想自己找到解决方案,但不知道如何开始
  • 我不知道你真正的 MainViewController 在哪里,在你的视图控制器层次结构中。只有你知道。使用这些知识,您可以编写一个表达式,通过视图控制器层次结构获取对它的引用。我在这里举个例子来解决这个问题:apeth.com/swiftBook/ch04.html#SECinstanceRefs 你犯的错误与我的“合法但愚蠢”的代码注释相同。我的讨论描述了一种特殊情况;但是您需要根据实际的视图控制器层次结构和 MainViewController 在其中的位置找出正确的表达式。
  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多