Swift 无法比较图像,其中一个来自UIButton

Swift 无法比较图像,其中一个来自UIButton,swift,uibutton,Swift,Uibutton,我知道如何获得按钮的图像,但在这里似乎不起作用: @IBAction func checkButtonClicked(_ sender: UIButton) { if sender.image(for: .normal) == #imageLiteral(resourceName: "btn_check_off_normal_holo_light") { sender.setImage(#imageLiteral(resourceName: "btn_check_on_f

我知道如何获得按钮的图像,但在这里似乎不起作用:

@IBAction func checkButtonClicked(_ sender: UIButton) {
    if sender.image(for: .normal) == #imageLiteral(resourceName: "btn_check_off_normal_holo_light") {
        sender.setImage(#imageLiteral(resourceName: "btn_check_on_focused_holo_light").withRenderingMode(.alwaysOriginal), for: .normal)
    } else {
        sender.setImage(#imageLiteral(resourceName: "btn_check_off_normal_holo_light").withRenderingMode(.alwaysOriginal), for: .normal)
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "UserCell"

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? UsersTableViewCell else {
        fatalError("The dequeued cell is not an instance of SelectTableViewCell.")
    }

    cell.checkButton.setImage(#imageLiteral(resourceName: "btn_check_off_normal_holo_light").withRenderingMode(.alwaysOriginal), for: .normal)
    return cell
}
我在CellForRow中设置按钮图像按钮位于动态表视图中的单元格中。在模拟器中,我可以看到正在设置图像。但是,这段代码不运行:

if sender.image(for: .normal) == #imageLiteral(resourceName: "btn_check_off_normal_holo_light") {
    sender.setImage(#imageLiteral(resourceName: "btn_check_on_focused_holo_light").withRenderingMode(.alwaysOriginal), for: .normal)
}
设置断点告诉我Xcode会直接跳过if语句中的代码:即使图像显然已设置为if语句中的图像


我想知道我是否遗漏了一些非常简单的东西?

你的一般方法是不正确的。您不应该试图检查按钮的当前图像来切换图像,而应该在数据模型中使用一个标志来填充表视图

您的cellForRowAt中需要此标志,以便在滚动时知道在每个单元格上显示哪个图像


然后,选中的checkButtonClicked只需切换给定行的标志,然后告诉表视图重新加载该行。

因此您的问题不会得到图像。您的问题是试图将按钮的图像与新的UIImage实例进行比较。是的……我想是的……哦,也许我应该编辑我的问题@RMADDYYYI-在你的牢房里使用警卫和致命错误是毫无意义的。只需在没有守卫的情况下进行强制施放。无论哪种方式,您都会遇到崩溃,但代码要少得多。@rmaddy谢谢您提供的信息。我将在Xcode中编辑我的代码,但问题暂时还可以…谢谢,但你知道我的旧代码为什么不起作用吗?因为比较UIImage实例实际上并不比较图像数据,只比较指针。那么如何比较实际图像呢?你可以得到PNG数据表示形式,并比较我认为的数据实例。