user3658023
user3658023

Reputation: 31

Using IF statement to test the ON/OFF setting of iOS Switch Control

I am new to Objective-C, but use JavaScript and a lot of VB.NET and some C for firmware development. I am writing beginner level Apps and in this case, have a SWITCH control on my View. I want to know how to use an IF statement to test it's ON/OFF state. Sample code is best as I am legally blind and have difficulty reading lots of text online.

Same issue for the Stepper control (The control with the +/_ buttons used to increment / decrement values.)

Thanks.

Upvotes: 0

Views: 2574

Answers (2)

Preson
Preson

Reputation: 244

first add a target to the switch for event UIControlEventValueChanged after adding the switch to your view, then use the switch's property to determine its state,

 [mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];

- (void) switchToggled:(id)sender {
        UISwitch *mySwitch = (UISwitch *)sender;
        if ([mySwitch isOn]) {
            NSLog(@"its on!");
        } else {
            NSLog(@"its off!");
        }
    }

Upvotes: 1

Pfitz
Pfitz

Reputation: 7344

UISwitch does have a property on (check the docu here: UISwitch class reference) so check the property (note that the getter is named differently (isOn)):

@property(nonatomic, getter=isOn) BOOL on

So one would check the switch like this:

if ([switch isOn])
{}
else
{}

Upvotes: 5

Related Questions