Reputation: 1127
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
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