I have UISwitch named sosSwitch thas saves value in NSUserDefaults key: MySwitch and I have UIButton named sosBtn. How can I show/hide sosBtn depending on the switch value that was saved in NSUserDefaults? And where I need to put the code? In viewDidLoad? Thank you!
Asked
Active
Viewed 5,784 times
1 Answers
2
Assuming that you already have:
@property (retain, nonatomic) IBOutlet UIButton *sosBtn;
@property (retain, nonatomic) IBOutlet UISwitch *sosSwich;
- (IBAction)sosSwitch:(id)sender;
Try this:
-(void)viewDidLoad
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"MySwitch"])
{
self.sosBtn.hidden = NO;
[self.sosSwich setOn:YES animated:YES];
}
else
{
self.sosBtn.hidden = YES;
[self.sosSwich setOn:NO animated:YES];
}
}
- (IBAction)sosSwitch:(id)sender
{
UISwitch *mySosSwitch = (UISwitch *)sender;
if (mySosSwitch.on)
{
self.sosBtn.hidden = NO;
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"MySwitch"]; //YES means sosBtn should be visible
[[NSUserDefaults standardUserDefaults] synchronize];
}
else
{
self.sosBtn.hidden = YES;
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"MySwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}

user523234
- 14,323
- 10
- 62
- 102
-
Ok, I understand.. but if my switch located in modal view controller and button in view, how can I do the same? – Pavel Kaljunen May 03 '12 at 20:56
-
1In that case you will need to implement the optional delegate method. Check out my answer to this SO that had an example of delegate method callback. http://stackoverflow.com/questions/8606674/uimodaltransitionstylepartialcurl-doesnt-get-back-to-previous-state-not-dismi/8607949#8607949 – user523234 May 04 '12 at 18:45