简体   繁体   中英

How to save UIButton IBAction to UserDefaults with Codable in my static checklist, swift?

How can I save the boolean value from when the user clicking on a checkbox (UIButton) in my checklist on a storyboard tableViewController?

have tried a lots of different tutorials but I don't get it because I have a boolean value and not a string ??? :S

The checklist app is complete and working but when checking boxes it does not get saved. when unchecking that should also get saved.

code for one of the 300 boxes I want to save:

    @IBAction func check1002Tapped(_ sender: UIButton) {
    if sender.isSelected {sender.isSelected = false }
    else {sender.isSelected = true }
}

insert saving logic code after button tapped.

@IBAction func check1002Tapped(_ sender: UIButton) {
    if sender.isSelected {
        sender.isSelected = false
    }
    else {
        sender.isSelected = true
    }
    UserDefaults.standard.setValue(sender.isSelected, forKey: "check1002Selected")
}
    

and load button state before button appear.

override func viewDidLoad() {
    super.viewDidLoad()
    button.isSelected = UserDefaults.standard.bool(forKey: "check1002Selected")
}

To any other beginners out there like me:

 UserDefaults.standard.setValue(sender.isSelected, forKey: "check1002Selected")

the key can be any words you choose it seems to be created here.

button.isSelected = UserDefaults.standard.bool(forKey: "check1002Selected")

where the "button" text is you write what you have named your @IBOutlet for the button you want to save. :D worked for me, happy happy beginner :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM