[英]Save UISwitch state even if the app gets restarted
I am trying to save the switch statement in objective-c but it will go back to the default state (which is off) whenever I reopen the app or go to another page and come back to the page that has switch我正在尝试将 switch 语句保存在 Objective-c 中,但是每当我重新打开应用程序或转到另一个页面并返回到具有 switch 的页面时,它都会返回到默认状态(关闭)
@property (strong, nonatomic) IBOutlet UISwitch *switch1;
@property (strong, nonatomic) IBOutlet UISwitch *switch2;
@property (strong, nonatomic) IBOutlet UISwitch *switch3;
I have 3 switches and I have 3 IBOutlets for them.我有 3 个开关,它们有 3 个 IBOutlets。 I have tried some codes to save the state but it did not work.
我尝试了一些代码来保存状态,但没有用。 How can I get them to work?
我怎样才能让他们工作?
You need to do two things:你需要做两件事:
1: Save the state of the switch when it changes: 1:保存开关改变时的状态:
-(IBAction) switchChanged:(UISwitch *)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:sender.isOn forKey:@"MySwitch"];
}
2: Fetch the state of the switch when your view controller loads: 2:当你的视图控制器加载时获取开关的状态:
-(void) viewDidLoad {
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
switch1.isOn = [defaults boolForKey:@"MySwitch"];
}
You can solve it by storing their states locally and checking the stored value every time you present the UISwitch
.您可以通过在本地存储它们的状态并在每次呈现
UISwitch
时检查存储的值来解决它。
Swift 4:斯威夫特 4:
UserDefaults.standard.set(<#Switch#>.isOn, forKey: "switch_name_here")
let value = UserDefaults.standard.value(forKey: "switch_name_here")
// Then you compare if value == true and set <#Switch#>.isOn = /* stored state */
Objective C:目标 C:
NSString *valueToSave = @"YES"; // or "NO" if switch is off.
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"switch_name_here"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"switch_name_here"];
// Then you compare to "YES" or "NO" and set [<#Switch#> setOn: /* stored state */]
Note:笔记:
After you get the stored value, you update the UISwitch
state.获得存储的值后,更新
UISwitch
状态。 You should store their values remotely if you have a login/register system or if you want this data to be updated in multiple devices.如果您有登录/注册系统,或者您希望在多个设备中更新此数据,则应远程存储它们的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.