Reputation: 73
I am learning UserDefaults, and I am using UserDefaults to store button state in them and use them on re-launching application.
My viewController has two button on which click the button image is changed. Function which represents button targets:
extension DetailViewController{
@objc func checkButtonTapped(sender: UIButton) {
detailViewModel?.watchedButtonPressed(sender: sender)
setupButton(sender: sender, button: .check)
}
@objc func favoriteButtonTapped(sender: UIButton) {
detailViewModel?.favoriteButtonPressed(sender: sender)
setupButton(sender: sender, button: .favorite)
}
}
Functions which are changing buttons states and save state value in UserDefault.
func watchedButtonPressed(sender: UIButton){
sender.isSelected = !sender.isSelected
UserDefaults.standard.setValue(sender.isSelected, forKey: "mvvmCheck\(movieIndex ?? 0)")
}
func favoriteButtonPressed(sender: UIButton){
sender.isSelected = !sender.isSelected
UserDefaults.standard.setValue(sender.isSelected, forKey: "mvvmFavorite\(movieIndex ?? 0)")
}
Function which change button image when its clicked:
func setupButton(sender: UIButton, button: buttonType){
switch button {
case .favorite:
sender.setImage(UIImage(systemName: "star"), for: .normal)
sender.setImage(UIImage(systemName: "star.fill"), for: .selected)
case .check:
sender.setImage(UIImage(systemName: "checkmark.seal"), for: .normal)
sender.setImage(UIImage(systemName: "checkmark.seal.fill"), for: .selected)
}
}
Function to setup buttons images when launching application:
func setupButtons(){
buttonChecked.isSelected = UserDefaults.standard.bool(forKey: "mvvmCheck\(detailViewModel?.movieIndex ?? 0)")
buttonFavorite.isSelected = UserDefaults.standard.bool(forKey: "mvvmFavorite\(detailViewModel?.movieIndex ?? 0)")
setupButton(sender: buttonChecked, button: .check)
setupButton(sender: buttonFavorite, button: .favorite)
}
But my values are not stored well when I am clicking (on app re-launch some buttons dont have valid picture (value) and some have) Should I use button tags to achieve this? Is problem if I am sending sender value through functions calls?
Upvotes: 2
Views: 190
Reputation: 150745
Although I don't think you should be using UserDefaults to store this information the problem is the way you are setting the value to UserDefaults.
You are using
UserDefaults.standard.setValue(...
If you command click on setValue
in Xcode, you'll see that you are taken to the function in Foundation.NSKeyValueCoding
. You should instead be using the correct UserDefaults function
UserDefaults.standard.set(sender.isSelected, ...
Which properly encodes the type.
Upvotes: 1