Search code examples
iosuibuttonparentviewcontrollerchildviewcontroller

iOS Access parentViewController to change the State of a UIButton setSelected:YES


I have a UIButton in MainViewController.
MainViewController has a childViewContoller.

I need to access the UIButton (tcButton) property in MainViewController FROM the childViewController and set it to setSelected:YES in viewDidLoad. I have the following code in my ChildViewController.m file and it's not working.

#import "ChildViewController.h"
#import "MainViewController.h"
#import "CoreData.h"

@interface ChildViewContoller () 
@property (nonatomic, strong) CoreData *coreData;
@property (nonatomic, strong) MainViewController *mainViewController;
@end

@implementation ChildViewController
@synthesize coreData, mainViewController;

-(void)viewDidLoad 
{
    [super viewDidLoad];
    self.managedObjectContext = [(STAppDelegate *)[[UIApplication sharedApplication]  delegate] managedObjectContext];
    [[(mainViewController *)self.parentViewController tcButton] setSelected:YES];
}

Solution

  • Your code is kind of a mess. Why are you creating a new instance of yourself in viewDidLoad? This makes no sense. If ChildViewController is truly a child view controller, then you can access the parent with self.parentViewController. You only need one line in the viewDidLoad:

    -(void)viewDidLoad // Line 4
    {
    
        [[(MainViewController *)self.parentViewController tcButton] setSelected:YES]; // Line 8
    }