Mansour
Mansour

Reputation: 535

Save UIButton state NSUserDefaults

I've a UIButton inside UITableViewCell. After a user touch on this button, I would like to disable it . Here's the code that I use:

    class TextCell: UITableViewCell {
    var buttonstate:Bool = true
    [...]

-

      @IBAction func ButtonPressed(sender: AnyObject) {
                self.likesButton.enabled = false
                NSUserDefaults.standardUserDefaults().setObject(false, forKey: "buttonstate")
                NSUserDefaults.standardUserDefaults().synchronize()
}

and then:

     override func awakeFromNib() {

            var buttonstate: [String]? = NSUserDefaults.standardUserDefaults().objectForKey("buttonstate") as? [String]

            if((buttonstate) != nil){

                self.likesButton.enabled = false

            }
            else{
                self.likesButton.enabled = true

            }
}

Unfortunately the code doesn't work. (the buttons is stil enabled after a touch). Thanks for your help and sorry for the question I just start,..

Upvotes: 0

Views: 565

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Update your code like below into your awakeFromNib function:

var buttonstate = NSUserDefaults.standardUserDefaults().objectForKey("buttonstate") as Bool
self.likesButton.enabled = buttonstate

Hope it helps.

Upvotes: 1

Related Questions