保存并加载UISwitch状态 [英] Save and Load UISwitch state
问题描述
我想保存swtich状态并在程序重启时加载它。
I want to save the swtich state and load it when the program restarted.
[[NSUserDefaults standardUserDefaults] setBool:switchControl.on forKey:@"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
这是保存部分
BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
NSLog(@"%@",test?@"YES":@"NO");
if(test == YES)
[switchControl setOn:YES animated:YES];
else
[switchControl setOn:NO animated:YES];
这是需要设置切换到其值的部分。我在viewdidload中执行了此操作方法,因为当我关闭应用程序并重新启动它时,我希望开关的状态设置保存的部分。
This is the part that is need to be set the switch to its value.I did this in viewdidload method because when i close the application and restarted it i want the state of the switch set the saved part .
但是它仍然显示默认部分可以帮助我设置它?
But it is still showing the default part can u help me to set it?
推荐答案
您是否将交换机创建为具有属性的IBOutlet?如果是这样,我认为您的问题是您不要将 switchControl
称为 self.switchControl
。
Did you create the switch as an IBOutlet with properties? If so, I think your problem is that you dont refer to your switchControl
as self.switchControl
.
然后您的正确保存声明将变为
Then your correct saving statement will become
[[NSUserDefaults standardUserDefaults] setBool:self.switchControl.on forKey:@"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
我会将设置开关的部分移动到 viewWillAppear
并且这样做:
I'd move the part that sets the switch into viewWillAppear
and do it like this:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
NSLog(@"%@",test?@"YES":@"NO");
[self.switchControl setOn:test animated:YES];
}
我也为你取了一个不必要的if语句。
I took out an unnecessary if-statement for you, too.
这篇关于保存并加载UISwitch状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!