Search code examples
objective-cuiviewcontrollerpropertiesparent-childparent

Can't set property in parentViewController


I have a view controller, MainViewController in which I have a UIButton as an IBOutlet that is connected up in Interface Builder

In the header I have

@interface MainViewController : UIViewController
{
    SettingsViewController *settingsViewController;
    UIButton *leftTextButton;
}

@property (nonatomic, retain) IBOutlet  UIButton *leftTextButton;

in the .m I have synthesised the property

@synthesize leftTextButton;

I then add a settings subview as follows

SettingsViewController *settingsViewController = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" 
                                                              bundle:nil];
[self.view.superview addSubview:settingsViewController.view];

Within the SettingsViewController I then try to update the title of the UIButton *leftTextButton in the parent view

[ ((MainViewController*) self.parentViewController).leftTextButton setTitle:@"Ahhhhh !!" forState:UIControlStateNormal];

Although this doesn't crash it doesn't work - the title of the button does not change.

Any help would be greatly appreciated


Solution

  • The parentViewController property is nil unless the view controller is presented modally, or is under a UINavigationController or a UITabBarController.

    Give your SettingsViewController a mainViewController property:

    @interface SettingsViewController
    ...
    @property (assign) MainViewController *mainViewController;
    

    Set it when you create the SettingsViewController:

    SettingsViewController *settingsViewController = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController"  bundle:nil];
    settingsViewController.mainViewController = self;
    

    Then you can use it to update the button title:

    [self.mainViewController.leftTextButton setTitle:@"Ahhhhh !!" forState:UIControlStateNormal];