How do I save a UIButton being selected (showing checkmark) and load it in iOS?


How do I save a UIButton being selected (showing checkmark) and load it in iOS?



I am a beginner and the following is what code I have so far. When clicking the button, it'll switch between the checkmark and the empty box (that's good). However, when exiting the app, the button won't save the state of being selected (check marked).



Attached is all my code, so that you can clearly see what's going on.


import UIKit

class ViewController: UIViewController {

@IBOutlet weak var checkMarkButton: UIButton!

let save = "save"

override func viewDidLoad() {
super.viewDidLoad()
if UserDefaults.standard.bool(forKey: "save") == true {
checkMarkButton.setImage(#imageLiteral(resourceName: "greyChecked"), for: .normal)

}else{

checkMarkButton.setImage(#imageLiteral(resourceName: "greyUnchecked"), for: .normal)

}
}




@IBAction func checkMarkAction(_ sender: UIButton) {
UserDefaults.standard.set(true, forKey: "save")
}


}



video of what is happening




1 Answer
1



Give the image name directly ,I tested my answer it is working


override func viewDidLoad() {
super.viewDidLoad()

if UserDefaults.standard.bool(forKey: "checkBoxSave01") == true {
checkBoxButton1.setImage(#imageLiteral(resourceName: "id"), for: .normal)

}else{
checkBoxButton1.setImage(#imageLiteral(resourceName: "phone"), for: .normal)
}
}
var isFirstClick = true
@IBAction func checkBoxTapped(_ sender: UIButton) {
if isFirstClick{
checkBoxButton1.setImage(#imageLiteral(resourceName: "id"), for: .normal)
UserDefaults.standard.set(true, forKey: "checkBoxSave01")
ifFirstClick = false
}else{
checkBoxButton1.setImage(#imageLiteral(resourceName: "phone"), for: .normal)
UserDefaults.standard.set(false, forKey: "checkBoxSave01")
isFirstClick = true
}

}



Once you click on button checkBoxSave01key value will be true until you delete the app.


checkBoxSave01





I have updated the code above. I decided to make a whole new Xcode project and use the same images. However, it still isn't saving for me and if you follow the link up above, you can see what I'm seeing when I run it.
– IanSp
Jun 30 at 4:50





@lanSp do you want to change button image in every button actions.
– Malleswari
Jun 30 at 5:45





Yes, like a checklist. I want to be able to check and uncheck and save which ever one is chosen.
– IanSp
Jun 30 at 5:48






updated my answer.
– Malleswari
Jun 30 at 5:54





In button action you are saving checkBoxSave01 key value true, but you are not setting image to button.
– Malleswari
Jun 30 at 5:58







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift