Jig Dagod
Jig Dagod

Reputation: 1

Toggle button custom image

I'm fairly new to coding and Xcode. I used the code below to make a button toggle from an on/off image. When I run the app on the iPad, it starts in the off position which I want. When I press the button it goes to the on position which is what I want. But when I press the button again it doesn't go back to the off position. It kinda of looks like it's a spring action and just stays in the on position.

I used the print to see what it's doing and it just displays the I am selected each time I press it.

I'm using Xcode 9.1 and swift

Inside my ViewController

@IBOutlet weak var toggleButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    let normalImage = UIImage(named: "red_switch_off_button.png")
    let selectedImage = UIImage(named: "red_switch_on_button.png")

    toggleButton.setImage(normalImage, for: .normal)
    toggleButton.setImage(selectedImage, for: .selected)
}

@IBAction func didPressButton(_ sender: UIButton) {
    if toggleButton.isSelected {print("I am selected.")}
    else {print("I am not selected.")}
}

Upvotes: 0

Views: 1861

Answers (2)

Will Boland
Will Boland

Reputation: 144

This is because when you click the button, it doesn't act like a switch. It is "active" and will remain that way. You need to check if the button is selected, either by a bool such as selected where on every click it changes to the opposite value. Then, just switch images depending on the status of that bool.

Upvotes: 0

ahsumra
ahsumra

Reputation: 87

Please do the following:

@IBAction func didPressButton(_ sender: UIButton) {
    toggleButton.isSelected = !toggleButton.isSelected
    if toggleButton.isSelected {print("I am selected.")}
    else {print("I am not selected.")}
}

Upvotes: 1

Related Questions