UISwitch与NSUserDefault

时间:2014-07-22 05:29:46

标签: ios objective-c nsuserdefaults uiswitch

我的应用中有一个设置页面,我有一个UISwitch。我所需要的只是让开关ON / OFF状态保持使用NSUserDefault。最初我的开关是关闭的当我回到主视图并进入设置后开启设置,开关状态恢复为OFF。

这里是代码:

if ([indexPath row] == 4 && [indexPath section] == 0)//cellForRowAtIndexPath
    {

        UISwitch *myst =[[UISwitch alloc]initWithFrame:CGRectMake(170, 10, 30, 30)];
        [myst addTarget:self action:@selector(state:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:myst];

    }


-(IBAction)state:(UISwitch *)sender
{
    NSUserDefaults *standardDefaults =[NSUserDefaults standardUserDefaults];

    if (sender.tag == 0) {
        if (sender.on ==1) {
            [standardDefaults setObject:@"On" forKey:@"val"];

        }
    }else if(sender.on == 0){

        [standardDefaults setObject:@"Off" forKey:@"val"];
    }

    [standardDefaults synchronize];


}

在viewWillAppear中:

[super viewWillAppear:animated];

    NSUserDefaults *standardDefaults =[NSUserDefaults standardUserDefaults];
    if ([[standardDefaults stringForKey:@"val"]isEqualToString:@"On"]) {

        myst.on=YES;
    }else if ([[standardDefaults stringForKey:@"val"]isEqualToString:@"Off"]){

        myst.on=NO;
    }

我需要进行状态,即如果用户打开,即使切换视图或停止并运行应用程序,它也应该处于ON状态。如何使这种状态持续下去?

1 个答案:

答案 0 :(得分:3)

UITableview的cellForRowAtIndexPath 方法中设置UISwitch的状态。

在您的Tableview中,您必须设置开关状态,

修改

if ([indexPath row] == 4 && [indexPath section] == 0)//cellForRowAtIndexPath
{

    UISwitch *myst =[[UISwitch alloc]initWithFrame:CGRectMake(170, 10, 30, 30)];
    [myst addTarget:self action:@selector(state:) forControlEvents:UIControlEventValueChanged];

// You have to set your older state of UISwitch here. 

      NSUserDefaults *standardDefaults =[NSUserDefaults standardUserDefaults];
     if ([[standardDefaults stringForKey:@"val"]isEqualToString:@"On"]) {

        myst.on=YES;
     }else if ([[standardDefaults stringForKey:@"val"]isEqualToString:@"Off"]){

        myst.on=NO;
     }
    [cell.contentView addSubview:myst];

}