【问题标题】:UISwitch with NSUserDefaultUISwitch 与 NSUserDefault
【发布时间】:2014-07-22 05:29:45
【问题描述】:

我的应用中有一个设置页面,其中有一个UISwitch。我只需要使用NSUserDefault 使开关状态保持在ON/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];


}

IN 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;
    }

我需要设置状态,即如果用户打开它,即使在切换视图或停止并运行应用程序之后,它也应该处于打开状态。如何让这种状态持续存在?

【问题讨论】:

    标签: ios objective-c nsuserdefaults uiswitch


    【解决方案1】:

    没有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];
    
    }
    

    【讨论】:

    • 您的意思是初始状态为“myst.on=NO;”对吗?
    • 否,您在 NSuserDefault 中存储的状态。
    • 你必须从 userDefaults 设置它的状态。检查编辑的答案。
    • 使用 NSUserDefaults 的 registerDefaults 方法在 AppDelegate 中为 val 设置初始 OFF。
    • 谢谢 .. 但它不起作用。当我返回并进入设置状态时,状态会变回来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2016-08-05
    • 2013-01-07
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    相关资源
    最近更新 更多