Search code examples
iosswift3

Unable to change image for the button in swift 3?


In my code for checkmark I used button to change images for selected and unselected but unable to implement if I click on it's changing to unchecked but again selecting button it's unable to change to check image can anyone help me how to resolve this ?

var checkedImage = UIImage(named: "check")! as UIImage
var uncheckedImage = UIImage(named: "uncheck")! as UIImage
var isChecked: Bool = true
var checkMarkSelected = 0

checkMarkButton.addTarget(self, action: #selector(checkMarkAction(button:)), for: .touchUpInside)

func checkMarkAction(button : UIButton) {
        if isChecked == true {
            checkMarkButton.setImage(checkedImage, for: .selected)
            isChecked = false
            checkMarkSelected = 1
        }
        else {
            checkMarkButton.setImage(uncheckedImage, for: .normal)
            isChecked = true
            checkMarkSelected = 0
        }
    }

Solution

  • Step 1: Select your CheckUIButton and set Image “Uncheck” (state config must be Default in attribute inspector)
    Step 2: In attribute inspector change state config to Selected and set image “Check”
    Step 3: Put following code in your UIButton action.
    
    @IBAction func checkclick(_ sender: UIButton) {
    
            sender.isSelected = !sender.isSelected
    
        }