Search code examples
iosobjective-cuiviewcontrolleruiswitch

Pass UISwitch State from One View Controller to Another ViewController


I have a UISwith in a viewcontroller A. I want to pass the state of the UISwitch to viewcontroller B. I am using Objective C. This is the code I'm using in viewcontroller A:

if (![switchview isOn]) {
                NSLog(@"OFF");   
            } else {
                NSLog(@"ON");
                [comment setObject:@"YES" forKey:kESActivityPrivateKey];
            }

I need to save the value of the UISwitch in viewcontroller B.

Any help is appreciated.


Solution

  • Don't try to access another view controller's view hierarchy directly. You should treat another view controllers views (and a switch is a kind of view) as private.

    Set an IBAction on your switch that points to the owning view controller. In that action save the sate of the switch to a property of your view controller.

    You can then access the property from the other view controller.