Mike Schmidt Mike Schmidt - 1 year ago 48
iOS Question

Problems Linking Up a Switch in Xcode?

I am having trouble linking up a switch. I understand how to connect the switch as an outlet and have it have actions change the boolean state of a value, but I need the switch to perform an action in a different view controller.

Here's the situation: I have a main table view controller, called View Controller A. I have a second view controller, lets call it view controller B, that controls a menu sidebar (on a regular view controller, not a table view) triggered by a bar item. I want to be able to open up the menu, hit a switch in the sidebar, and have something change in the main table view that is controlled by view controller A.

Is there any way that I can accomplish this? I seem to have no way of accessing or changing the IBOutlets in View Controller A from B. Is there a way that I can have the action in B linked with the switch change the boolean state of a value, and have an action waiting in controller A that will respond to a change in boolean? I am not sure how to solve this problem. Help is appreciated!

Answer Source

You should use delegation pattern. You'll have an action waiting in controller A, but instead of responding to value changed in B the action will be triggered by B when appropriate


// Create delegate protocol and property
@protocol ViewControllerBDelegate <NSObject>
    - (void)switchPressed:(BOOL)switchStatus;

@interface ViewControllerB : NSObject
    @property (nonatomic,weak) id<ViewControllerBDelegate> delegate;


// When switch is tapped, call delegate method if it is implemented by delegate object
- (IBAction)flip: (id) sender {
    UISwitch *onoff = (UISwitch *) sender;
    if ([self.delegate respondsToSelector:@selector(switchPressed:)]) {
        [self.delegate switchPressed:onoff.on];


// Conform to ViewControllerB protocol
#import ViewControllerB.h

@interface ViewControllerA : NSObject,ViewControllerBDelegate


// Set self (VC A) as VC B's delegate
- (void)ViewDidLoadOrSomeOtherFunction {    
    ViewControllerB *vcB = [[ViewControllerB alloc] init];
    vcB setDelegate = self;

// Implement delegate method
- (void)switchPressed:(BOOL)switchStatus {
    if (switchStatus) {
        // Make changes on VC A