Home > Software engineering >  How to add custom uiButton Class checkbox to User defaults to save state? - Swift
How to add custom uiButton Class checkbox to User defaults to save state? - Swift

Time:10-19

So I'm creating an application that will need a checklist so I was able to create a custom checkbox class to make the checkbox and add that onto my uiButtons which work fine but upon opening up and building the app again it does not save state of the checkbox so how can I make it that the button input will be added to user defaults using this code so when I open the app again the checkbox input will have saved and be returned?

import UIKit

class CheckBox: UIButton {
    
    //images
    let checkedImage = UIImage(named: "checkedd_checkbox")
    let unCheckedImage = UIImage(named: "uncheckedd_checkbox")
    
    //bool propety
    @IBInspectable var isChecked:Bool = false{
        didSet{
            self.updateImage()
        }
    }

    
    override func awakeFromNib() {
       self.addTarget(self, action: #selector(CheckBox.buttonClicked), for: UIControl.Event.touchUpInside)
       self.imageView?.contentMode = .scaleAspectFit
       self.imageEdgeInsets = UIEdgeInsets(top: 5.0, left: 0.0, bottom: 5.0, right: 50.0)
       self.updateImage()
    }
    
    
    func updateImage() {
        if isChecked == true{
            self.setImage(checkedImage, for: [])
        }else{
            self.setImage(unCheckedImage, for: [])
        }

    }

    @objc func buttonClicked(sender:UIButton) {
        if(sender == self){
            isChecked = !isChecked
        }
    }

}

CodePudding user response:

Just set Userdefault in buttonClicked action like

@objc func buttonClicked(sender:UIButton) {
     if(sender == self){
        isChecked = !isChecked
      UserDefaults.standard.set(isChecked, forKey: "give a spesific name here")

    }
 }

And check button is selected status in

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    let getCheckStatus = UserDefaults.standard.bool(forKey: "given spesific name here")
     self.isChecked = getCheckStatus
     updateImage()
  }

If you load this view from storyboard or xib use required init?(coder aDecoder: NSCoder) , If you add manually use override init(frame: CGRect) {... }

  • Related