gunas
gunas

Reputation: 1907

set image for UIbutton selected state not working in swift 4

I have swift4 in my project and set an image for button state selected. But, when the button is in the selected state the image is not getting changed. I have changed the image in storyboard as well as code but nothing works.

ChkBoxBtn.setImage(UIImage(named: "unCheck"), for: [])
        ChkBoxBtn.setImage(UIImage(named: "alertCheck"), for: .selected)

enter image description here

enter image description here

Upvotes: 1

Views: 3188

Answers (2)

Chanaka kasun bandara
Chanaka kasun bandara

Reputation: 71

Create an action outlet to view controller, then add the below code. This helps you to switch between selected and deselected states easily.

@IBAction func ChkBoxBtnTapped(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
}

Upvotes: 1

OverD
OverD

Reputation: 2632

When a user taps a button the associated action will be called.

Within that action or method you have to change the .isSelected property of the concerned UIButton and set it to true

yourButton.isSelected = true

This will then reflect the image you have set in storyboard for the selected state of the UIButton

Upvotes: 5

Related Questions