简体   繁体   English

保存并加载 UISwitch state

[英]Save and Load UISwitch state

I want to save the swtich state and load it when the program restarted.我想保存 swtich state 并在程序重新启动时加载它。

[[NSUserDefaults standardUserDefaults] setBool:switchControl.on forKey:@"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];

This is the saving part这是节省部分

BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
NSLog(@"%@",test?@"YES":@"NO");
if(test == YES)
    [switchControl setOn:YES animated:YES];
else
     [switchControl setOn:NO animated:YES];

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.这是需要将开关设置为其值的部分。我在 viewdidload 方法中执行此操作,因为当我关闭应用程序并重新启动它时,我希望开关的 state 设置保存的部分。

But it is still showing the default part can u help me to set it?但它仍然显示默认部分你能帮我设置它吗?

Did you create the switch as an IBOutlet with properties?您是否将开关创建为具有属性的 IBOutlet? If so, I think your problem is that you dont refer to your switchControl as self.switchControl .如果是这样,我认为您的问题是您没有将switchControl称为self.switchControl

Then your correct saving statement will become那么你正确的储蓄报表就会变成

[[NSUserDefaults standardUserDefaults] setBool:self.switchControl.on forKey:@"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];

I'd move the part that sets the switch into viewWillAppear and do it like this:我会将设置开关的部分移动到viewWillAppear中,并这样做:

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
  NSLog(@"%@",test?@"YES":@"NO");
  [self.switchControl setOn:test animated:YES];
}

I took out an unnecessary if-statement for you, too.我也为你取出了一个不必要的 if 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM