Kauna Mohammed
Kauna Mohammed

Reputation: 1127

How can I get the UIButton state to be different for each tableView row?

In this code I have a selected state and deselected state for my button. When the button has been pressed, it changes to green and when pressed again it changes to red to represent a deselected state.

However, all this is in a DetailViewController and when I select a particular row from my tableView then click the button to show green and go back and try a different row, the button shows green on this other row which signifies that I've pressed it(I haven't). I was wondering if there was a way to only show green for detailView of the row I selected and red for the others?

 let defaults = UserDefaults.standard

// Outlets
@IBOutlet weak var goingButton: UIButton!

// Actions
@IBAction func goingButtonTapped(_ sender: UIButton) {

    goingButton.isSelected = !goingButton.isSelected

    if goingButton.isSelected == true {
        goingButton.setImage(UIImage(named: "goingSelected"), for: UIControlState.selected)
        defaults.set(true, forKey: "going")
        defaults.synchronize()
        defaults.bool(forKey: "going")
        print("defaults: \(defaults)")
    } else if goingButton.isSelected == false {
        goingButton.setImage(UIImage(named: "goingDeselected"), for: UIControlState.normal)
        defaults.set(false, forKey: "going")
        defaults.synchronize()
        defaults.bool(forKey: "going")

    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    goingButton.setImage(UIImage(named: "goingDeselected"), for: UIControlState.normal)
    if defaults.bool(forKey: "going")
{
    goingButton.isSelected = true
    goingButton.setImage(UIImage(named: "goingSelected"), for: UIControlState.selected)

}
}

Upvotes: 1

Views: 153

Answers (1)

Abhishek Jain
Abhishek Jain

Reputation: 4739

Try this -

override func viewDidLoad() {
    super.viewDidLoad()

    goingButton.setImage(UIImage(named: "goingDeselected"), for: UIControlState.normal)
    if defaults.bool(forKey: "going")
    {
        goingButton.isSelected = true
        goingButton.setImage(UIImage(named: "goingSelected"), for: UIControlState.selected)

    }
}

Upvotes: 1

Related Questions