I\'m trying to complete my favorite button by saving it state even when i quit the view \\ App . it will be great if anyone could show me how can i do this, I\'m using
Every time you use UserDefaults.standard.set
you need sync , add UserDefaults.standard.synchronize()
.
To remove/delete a saved value use UserDefaults.standard.removeObject(forKey: "YOUR_KEY")
here is your func
@IBAction func button(sender: UIButton) {
sender.isSelected = !sender.isSelected
//one thing i tried , doesn't work :
UserDefaults.standard.set(true,forKey: "isSaved")
UserDefaults.standard.synchronize()
if let Favoritebutton = sender as? UIButton {
if Favoritebutton.isSelected {
// set selected
Favoritebutton.isSelected = true
UserDefaults.standard.set(true, forKey: "MY_FAV_KEY")
UserDefaults.standard.synchronize()
//Add to favorites
} else {
// set deselected
Favoritebutton.isSelected = false
UserDefaults.standard.set(false, forKey: "MY_FAV_KEY")
UserDefaults.standard.synchronize()
//remove from Favorites
}
}
}