Reputation: 187
So I have a button
which changes its image upon clicking. I would like to save the state of the button
so that, when user reopens the app again, the button
will display it's last state.
Below is my code:-
- (IBAction)xButtonOnPressed:(id)sender {
[self.xButtonLabel setImage:[UIImage imageNamed:@"x_did-not-take_marked.png"] forState:UIControlStateSelected];
[self.xButtonLabel setImage:[UIImage imageNamed:@"x_did-not-take.png"] forState:UIControlStateNormal];
self.xButtonLabel.selected = !self.xButtonLabel.selected;
}
The problem with the code is that, it always goes back to UIControlStateNormal
after restarting the app. How can I save the last button state ?
Upvotes: 0
Views: 306
Reputation: 2149
use NSUserDefaults for this.
Objective C:
To store:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"BUTTON_STATE_NORMAL"];
To retrieve:
Bool isNormalState = [[NSUserDefaults standardUserDefaults]
boolForKey:@"BUTTON_STATE_NORMAL"];
if(isNormalState == true) {
//Do your thing.
}
swift 3:
To store:
UserDefaults.standard.set("Your_button_state", forKey: "Key") //setObject
To retrieve:
UserDefaults.standard.string(forKey: "Key")
There are lots of data type in this.Choose how you want to save>:)
Upvotes: 0
Reputation: 62686
Say you have a button called button:
UIButton *button;
// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];
Then later, after the app launches again...
// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];
Upvotes: 2