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];
}