и это мой первый вопрос здесь!
Я использую UIButton с функциональностью UISwitch и хочу сохранить / восстановить состояние UIButton.
ПОЖАЛУЙСТА, ПОМОГИТЕ!
Решено!
Спасибо, Калле и aBitObvious!
код, который я использую:
.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];
}