如何通过切换开关应用设置?

时间:2011-04-12 15:34:14

标签: cocoa-touch ios button switch-statement

  

可能重复:
  can anyone tell me how to use switch ?

嗨,我有两个观点

第一个视图包含main函数,第二个视图用于让用户更改第一个视图的设置。

我在第二个视图中插入一个开关,让用户更改第一个视图的设置

我有两个问题,如何使用开关为值设置YES和NO?然后,基于该值 第一种观点会有不同的反应?

P.S。我用导航方法更改视图,而不是添加子视图

提前致谢

假设我有以下代码

First View.m

- (IBAction) addValue:(id)sender
{
aValue ++;
}
//the following will react according to the setting on second view
If (????//Don't know what to put here to represent the switch is ON or OFF)
{ //whatever action}
else
{//whatever action}

第二个view.h

@interface
    //declaration of the switch
        - (IBAction) changeMode:(id)sender
    @end

第二次观看.m

    -(IBAction) changeMode:(id)sender
{
    //What to put here to switch ON and OFF ??
}

1 个答案:

答案 0 :(得分:4)

你可以这样做:

if ( self.mySwitch.on )
// do something

这里我假设mySwitch是UISwitch的一个实例。最好将切换值存储到NSUserDefaults,以便您可以从另一个视图中检索它。

这是您存储值的方式:

NSString *switchValue; 
if ( self.mySwitch.on ) 
    switchValue = @"YES";
else 
    switchValue = @"NO";

[[NSUserDefaults standardUserDefaults] setObject:switchValue forKey:@"switchValue"];
[[NSUserDefaults standardUserDefaults] synchronize];

这是检索值的方法:

BOOL switchState = [[[NSUserDefaults standardUserDefaults] objectForKey:@"switchValue"] boolValue];