I have taken UISwitch from interface builder. That time it's state is ON.After run application When I change it's position to OFF and go to other screen and again back to that screen, switch sates shows ON not OFF which i set previously. Any one can tell me how i can show UISwitch position or state which I set. Now it always show ON when I come to this switch screen. Please help me. Thanks in advance.
问题:
回答1:
When you change the value, save it to NSUserDefault, so when you come back that screen again, you look at the preferences value and set it to the switch
- (void)saveValue {
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences setBool:value forKey:@"switchOnOff"];
[preferences synchronize];
}
- (BOOL)readValue {
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
return [preferences boolForKey:@"switchOnOff"];
}
回答2:
Have an outlet for the UISwitch,
@property (retain, nonatomic) IBOutlet UISwitch *sswitch;
and make the connection.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if( [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"] )
{
[sswitch setOn:YES]
}
else
{
[sswitch setOn:NO]
}
}
And whenever the switch state is changed, save the value in NSUserDefaults
回答3:
When you change the switch state, store the value as integer in NSUserDefaults, and in viewDidAppear method of the viewController where your switch resides. Just set the switch state by getting value from NSUserDefaults like this
//store value to nsuserdefaulrs
[[NSUserDefaults standardUserDefaults] setBool:switch.on forKey:@"switchStatus"];
//get value from nsuserdefaulrs
[switch setOn:[[NSUserDefaults standardUserDefaults] boolForKey:@"switchStatus"]];
回答4:
You have to save values in
1. Model class
2. NSUserDefaults
3. Plist
4. Document file.
Best way would be Model class. You will get code easily for these in Stackoverflow.
回答5:
If it's a switch that you added in IB, you can just set its initial state there. Otherwise, after you've linked the switch to the IBOutlet, you can add in your viewDidLoad something like:
[savePass setOn:NO];
and it will set the switch to an off state. You need to make sure the switch is linked to the IBOutlet variable.