【问题标题】:How to apply setting by toggle switch? [duplicate]如何通过拨动开关应用设置? [复制]
【发布时间】:2011-04-12 15:34:13
【问题描述】:

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

嗨,我有两个观点

第一个视图包含主要功能,第二个视图用于让用户更改第一个视图的设置。

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

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

附:我用导航方法改变视图,而不是添加子视图

提前致谢

假设我有以下代码

第一个视图.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}

第二个视图.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 ??
}

【问题讨论】:

    标签: cocoa-touch ios button switch-statement


    【解决方案1】:

    你可以这样做:

    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];
    

    【讨论】:

    • 嗯,对不起,您有什么可以与我的代码相关的吗?
    • 好的,我编译它没有问题,但我发现当我切换回第一个视图后,我将开关切换到关闭,然后再次切换到第二个视图(开关按钮所在的位置)它没有t 存储状态,它仍然是“ON”。
    • 您应该在 viewDidLoad 方法中设置开关,方法是在用户首先更改后从 NSUserDefaults 读取。
    猜你喜欢
    • 2020-10-18
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多