views:

64

answers:

1

Hi all.. and this is my first question here !

I use UIButton with UISwitch functionality and i want to save/retrieve state of UIButton. Pls HELP!

Resolved!

Thanks Kalle and aBitObvious !

code i use :

.h

@interface RetinaViewController : UIViewController {
IBOutlet UIButton *mybutton;

}

-(IBAction) toggleUIButtonImage:(id)sender;


@end

.m

@implementation RetinaViewController

-(IBAction) toggleUIButtonImage:(id)sender{
NSString *value = @"ON";
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
UIImage *unselectedImage = [UIImage imageNamed: @"OFFa.png"];
UIImage *selectedImage = [UIImage imageNamed:@"ONa.png"];
    if ([sender isSelected]) {
    [sender setImage:unselectedImage forState:UIControlStateNormal];
    [sender setSelected:NO];
        value = @"OFF";
        [userPreferences setObject:value forKey:@"stateOfButton"];
}else {
    [sender setImage:selectedImage forState:UIControlStateSelected];
    [sender setSelected:YES];
    value = @"ON";
    [userPreferences setObject:value forKey:@"stateOfButton"];
}

[userPreferences synchronize];
}



- (void)viewDidLoad {

NSString *value = [[NSUserDefaults standardUserDefaults]  stringForKey:@"stateOfButton"];

// If value is nil - disable the switch
if (value == nil) { 
    mybutton.selected = NO;
}
// If value is equal to ON
else if ([value compare:@"ON"] == NSOrderedSame) {

    //NSLog(@"the switch is on");

    // Set the switch to ON
    mybutton.selected = YES;

} else {

    //NSLog(@"the switch is off");

    // Set the switch to OFF
    mybutton.selected = NO;
}


    [super viewDidLoad];
}
A: 

In the viewDidLoad of the view controller, put something like this:

NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
NSString *stateOfButton = [userPreferences stringForKey:@"stateOfButton"];
if ([stateOfButton isEqualToString:@"ON"])
{
    //set button state to "selected"
}
else
{
    //set button state to "not selected"
}
aBitObvious
this does not work !
Dorald
You also need to do [userPreferences synchronize] to actually SAVE the changes. That would be in your toggleUIButtonImage code, below the [userPreferences setObject: ...] line(s).
Kalle
Resolved..... Thank you guys.
Dorald
Feel free to point out how you resolved it too for other people who have the same problem and find their way here.
Kalle