Xcode:UIButton setImage不会更改按钮的图像

问题描述

注意:其他人也提出了类似的问题,但没有提供的答案可以解决我的问题。

这是我的代码

   @IBOutlet var testButton:UIButton!
    override func viewDidLoad() {
       self.testButton.setimage(UIImage(named: "icn_checkBox_")?.imageWithColor(color: CMStyle.darkBlueColor),for: .normal)
        self.testButton.setimage(UIImage(named: "icn_checked")?.imageWithColor(color: CMStyle.darkBlueColor),for: .selected)
        
    }
 @IBAction func testButtonAction(_ sender: Any) {
        print("INSIDE testButtonAction")
              self.testButton.isSelected = !self.testButton.isSelected
              print("self.testButton.isSelected: ",self.testButton.isSelected)
    }

这是按钮:

enter image description here


这些是按钮的特征:

enter image description here


这是用于.normal状态的 icn_checkBox _ 图片

enter image description here

这是用于.selected状态的 icn_checked 图片

enter image description here

testButtonAction中的代码被执行。所以我真的不明白为什么图像不改变(为什么按钮没有被选中)。

解决方法

您可以使用此:

$groups
,

您可以仅在情节提要中为按钮状态设置图像,其中默认= .normal和Selected = .selected

enter image description here

选择所选内容并在那里设置图像。如果您使用的是模板图片,则带有颜色的图片与tintColor相似