How to apply setting by toggle switch? [duplicate]

2020-03-31 06:04发布

问题:

This question already has an answer here:
Closed 8 years ago.

Possible Duplicate:
can anyone tell me how to use switch ?

Hi I have two view

the first view contains the main function and the second view is used to let the user change the setting on the first view.

I have insert a switch in second view to let user change a setting on the first view

I have two questions, how to use switch to set YES and NO for a value? and then, base on that value the first view will respond differently?

P.S. I change the view with navigation method , not add subview

Thanks in advance

lets say I have the following code

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}

second view.h

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

second view.m

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

回答1:

You can do this:

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

Here I assume mySwitch is an instance of UISwitch. It is a good idea to store switch value to NSUserDefaults so that you can retrieve it from another view.

This is how you store the value:

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

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

This is how you retrieve the value:

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