user3434008
user3434008

Reputation: 1

save UIButton state iOS

I have a UIButton

- (IBAction)checkButton:(id)sender {

if (!checked) {
    [checkBoxButton setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
    checked = YES;
} else if (checked) {
    [checkBoxButton setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
    checked = NO;
}

}

I want to save the user input, weather the button is checked or not, even after the app closes. Help me with codes anyone? I don't know the codes to use NSUserDefaults for saving BOOL state.

Upvotes: 0

Views: 747

Answers (4)

Jogendra.Com
Jogendra.Com

Reputation: 6454

My way is too easy .. You don't need to take any other variable. On initialise set your button tag ZERO and after use this.

  - (IBAction)checkButton : (id)sender {

      if ([sender tag] == 0) {
        [sender setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
        [sender setTag:1];
      } else   {
         [sender setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
        [sender setTag:0];
      }
  }

Thanks & Cheers .. May be helpfull..

Upvotes: 0

Socrates II
Socrates II

Reputation: 1

Here is an Example:

if ([[NSUserDefaults standardUserDefaults] boolForKey:hasLaunchedOnceKey])
{
    [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:hasLaunchedOnceKey];
    [[NSUserDefaults standardUserDefaults] synchronize]; //Saves the data
}

Where I have:

static NSString *hasLaunchedOnceKey = @"HasLaunchedOnce";

Declared before the @implementation statement.

See this for an extensive tutorial.

**Note: You do not need to declare anything in any sort of plist files afaik. You can simply check for and set these keys and they will be dynamically created if they don't exist. Works that way for me anyways.

Happy programming!

Upvotes: 0

Apurv
Apurv

Reputation: 17186

Use it by below way:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool: checked forKey:@"Status"];
[defaults synchronize];

To retrieve it,

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL state = [defaults boolForKey:@"Status"];

Upvotes: 1

Rugmangathan
Rugmangathan

Reputation: 3226

Set images for both Normal and selected state of a button as

[checkBoxButton setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateSelected];
[checkBoxButton setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];

and in IBAction set

- (IBAction)checkButton:(id)sender {

    if (!checked) {
        [checkBoxButton setSelected:NO];
        checked = YES;
    } else if (checked) {
        [checkBoxButton setSelected:YES];
        checked = NO;
    }

}

Upvotes: 0

Related Questions