0

在 ViewDidLoad

{
     NSLog(@"Switch Value %d",delegate.switchvalue);

    if(delegate.switchvalue==1)
    {
        [onoffswitch setOn:YES];
    }
    else
    {
        [onoffswitch setOn:NO];
    }

}

在设计中,

 onoffswitch=[[UISwitch alloc]initWithFrame:(CGRectMake(200, 8, 50, 33))];
    [onoffswitch addTarget:self action: @selector(flip:) forControlEvents:UIControlEventValueChanged];
   // [onoffswitch setOn:YES];

在切换方法中,

-(IBAction)flip:(id)sender


{

    if([sender isOn])
    {
        [onoffswitch setTag:1];
        NSLog(@"%d",[sender tag]);
        delegate.switchvalue=[sender tag];
        NSLog(@"%d",delegate.switchvalue);


        NSLog(@"ON");

        NSTimer *BirthTimer=[NSTimer scheduledTimerWithTimeInterval:86400.0 target:self selector:@selector(TimerTapped:) userInfo:nil repeats:YES];

        [BirthTimer fire];
    }
    else
    {
        NSLog(@"OFF");

    }
}

我的问题是,我将开关模式设置为 ON。如果我转到另一个视图,则再次更改为关闭模式。任何想法请帮助我。

感谢您的帮助。

使用 NSUserDefaults

-(IBAction)翻转:(id)发件人

{

[onoffswitch setTag:1];
delegate.switchvalue=[sender tag];
NSLog(@"%d",delegate.switchvalue);

if([sender isOn])
{

    NSLog(@"ON");
    isAlarm=1;
    NSLog(@"%d",isAlarm);

    NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [switchdefault setInteger:delegate.switchvalue forKey:@"Switchcontrol"];
    [switchdefault setBool:YES forKey:@"SwitchBool"];
    [switchdefault synchronize];


    NSTimer *BirthTimer=[NSTimer scheduledTimerWithTimeInterval:86400.0 target:self selector:@selector(TimerTapped:) userInfo:nil repeats:YES];

    [BirthTimer fire];
}
else
{
    NSLog(@"OFF");
    isAlarm=0;
    NSLog(@"%d",isAlarm);


}

}

在视图中将出现

NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];

if([switchdefault boolForKey:@"SwitchBool"])
{
    [onoffswitch setOn:YES animated:YES];
}
else
{
    [onoffswitch setOn:YES animated:YES];
}

在另一个视图的 ViewDidLoad 中

NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];

if ([switchdefault boolForKey:@"SwitchBool"])
{
    delegate.switchvalue=1;
}
[switchdefault synchronize];
4

2 回答 2

2

用于NSSUserDefault存储开关按钮的状态,并在将其添加到视图时再次从同一位置检索它...

切换后存储 1 ON,模式存储 0 OFF

[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"values"];

并像这样取回它,

NSInteger mode = [[NSUserDefaults standardUserDefaults] integerForKey:@"values"];

注意:我建议您在ViewWillAppear/ViewDidAppear.

于 2013-08-23T08:25:48.000 回答
0

如果您希望delegate.switchValue每次视图出现时都设置为开关,请尝试将此代码从 viewDidLoad 移动到 viewDidAppear:

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(delegate.switchvalue==1) 
    {
        [onoffswitch setOn:YES];
    }
    else
    {
        [onoffswitch setOn:NO];
    }
}
于 2013-08-23T08:25:08.140 回答