Search code examples
iosswiftxcodeuibuttontvos

Xcode: UIButton setImage does not change the image of the button


NOTE: Others have asked a similar question and none of the answers provided solved my problem.

Here's my code:

   @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)
    }

This is the button:
enter image description here.
These are the characteristics of the button:
enter image description here.
This is icn_checkbox_ image used for .normal state:
enter image description here This is icn_checked image used for .selected state: enter image description here

The code inside testButtonAction gets executed. So I don't really see why wouldn't the image change (Why doesn't the button become checked).


Solution

  • You can use this:

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