我设法更改了UISwitch的状态并保存到NSUserDefaults

我的UISwitch与主视图位于不同的视图中,当我在视图之间切换时,即使状态可能为OFF,我的UISwitch按钮也始终显示为ON。

- (IBAction)truthonoff:(id)sender {
    if(_truthonoff.on) {
        // lights on

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setValue:@"yes" forKey:@"truthonoff"];
        [defaults synchronize];

        self.status.text = @"on";
    }

    else {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setValue:@"no" forKey:@"truthonoff"];
        [defaults synchronize];

        self.status.text =@"off";
    }
}

这就是我在第二个视图控制器中加载按钮的方式:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
self.text.text=[defaults objectForKey:@"truthonoff"];

如何确定UISwitch状态代表NSUserDefaults中的值(即,当它为OFF时显示为OFF,而当ON显示为ON)?

最佳答案

试试这个:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[self.valueSwitch setOn:[[defaults objectForKey:@"truthonoff"] boolValue] animated:YES];
[self.valueSwitch addTarget:self action:@selector(stateSwitched:) forControlEvents:UIControlEventValueChanged];

stateSwitched中执行以下操作:
-(void)stateSwitched:(id)sender {
    UISwitch *tswitch = (UISwitch *)sender;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"truthonoff"];
    [defaults synchronize];
}

希望这可以帮助 .. :)

关于ios - 从NSUserDefaults加载UISwitch的状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22585526/

10-13 07:29