我如何使用NSUserDefaults保存按钮的状态?

时间:2015-08-06 18:18:09

标签: swift nsuserdefaults

基本上我想要做的是保存用户所做的选择(顶部按钮或底部按钮),这样当用户存在应用程序并返回时,他们的选择投票将被保存,并且他们不必重做它。 / p>

@IBAction func topButton(sender: AnyObject) {


    var nicebutton = sender as! UIButton

    nicebutton.enabled = false

    var nopebutton = nicebutton.superview?.viewWithTag(102) as! UIButton

    nopebutton.enabled = true



    let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
    let object = objectAtIndexPath(hitIndex)



    object.incrementKey("count")
    object.save()
    self.tableView.reloadRowsAtIndexPaths([hitIndex!], withRowAnimation: UITableViewRowAnimation.None)

}



@IBAction func bottomButton(sender: AnyObject) {

    var nopebutton = sender as! UIButton

    nopebutton.enabled = false

    var nicebutton = nopebutton.superview?.viewWithTag(101) as! UIButton

    nicebutton.enabled = true
    let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
    let object = objectAtIndexPath(hitIndex)
    object.incrementKey("count", byAmount: -1)
    object.save()
    self.tableView.reloadRowsAtIndexPaths([hitIndex!], withRowAnimation: UITableViewRowAnimation.None)
}

1 个答案:

答案 0 :(得分:0)

您只需在下方添加代码并设置按钮状态

即可
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "niceButtonEnabled");
NSUserDefaults.standardUserDefaults().synchronize()

当然,你需要在显示按钮之前获得。

if(NSUserDefaults.standardUserDefaults().boolForKey("niceButtonEnabled")){
   //enable the button which you selected before
}
希望它有所帮助。

更详细的版本..

  @IBAction func bottomButton(sender: AnyObject) {

   var nopebutton = sender as! UIButton

   if let nopeE =    NSUserDefaults.standardUserDefaults().boolForKey("nopeButtonEnabled") {
    //enable the button which you selected before
       nopebutton.enabled = nopeE
   }else{
       NSUserDefaults.standardUserDefaults().setBool(false, forKey: "nopeButtonEnabled");
       NSUserDefaults.standardUserDefaults().synchronize()
   }

   var nicebutton = nopebutton.superview?.viewWithTag(101) as! UIButton
   if let niceE =    NSUserDefaults.standardUserDefaults().boolForKey("niceButtonEnabled") {
       //enable the button which you selected before
        nicebutton.enabled = niceE
   }else{
       NSUserDefaults.standardUserDefaults().setBool(true, forKey: "niceButtonEnabled");
       NSUserDefaults.standardUserDefaults().synchronize()
   }
   let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
   let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
   let object = objectAtIndexPath(hitIndex)
   object.incrementKey("count", byAmount: -1)
   object.save()
   self.tableView.reloadRowsAtIndexPaths([hitIndex!], withRowAnimation:    UITableViewRowAnimation.None)
  }