title: Saving state of UIButton (checkbox) - Swift
body: <p>I'm a new developer and I'm making a to-do list app in Swift. I was able to figure out how to change the state of the <code>UIButton</code> (checkbox) on clicking. At the moment I'm trying to figure out how to save that state for when I exit the app or switch views and return. I was able to successfully save the text (to-do list tasks) by using <code>NSUserDefaults</code> and have also experimented with it on my buttons but cannot figure out how to get it to work.</p>
  
  <pre><code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  
  var myButton: Qbutton!
  
  override func viewDidLoad() {
      super.viewDidLoad()
  
      var isChecked = NSUserDefaults.standardUserDefaults().boolForKey("isBtnChecked") // here we obtain the last state of the button
      myButton.isChecked = isChecked
      self.view.addSubview(myButton)
  </code></pre>
  
  <p>I have the <code>UIButton</code> in a subclass of <code>QButton</code>.</p>
  
  <pre><code>class Qbutton: UIButton {
  
      var isSelected: Bool = defaults.boolForKey("isButtonChecked")
  
      // Images
      let selectedImage = UIImage(named: "Selected")
      let unselectedImage = UIImage(named: "Unselected")
  
  
      //Bool Property
      var isChecked:Bool = false{
          didSet{
              if isChecked == true{
                  self.setImage(selectedImage, forState: UIControlState.Normal)
              }else{
                  self.setImage(unselectedImage, forState: UIControlState.Normal)
              }
              defaults.setObject(isChecked, forKey: "isButtonChecked")
          }
      }
  
      override init(frame: CGRect){
      super.init(frame:frame)
      self.layer.masksToBounds = true
      self.setImage(unselectedImage, forState: UIControlState.Normal)
  
      self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
      self.isChecked = false
  }
  
  required init(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
  }
  
  func buttonClicked(sender: UIButton) {
      if(sender == self){
          if isChecked == true{
              isChecked = false
          }else{
              isChecked = true
          }
      }
  }
  }
  </code></pre>