CarlG
CarlG

Reputation: 47

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

Upvotes: 0

Views: 1698

Answers (2)

Dennis Bliefernicht
Dennis Bliefernicht

Reputation: 5157

If you just add the view controller's view in the parent view, the view controller will have no idea of its parent view controller, thus the parentViewController property is nil. You also have to add your SettingsViewController to your MainViewController via addChildViewController: and then notify the SettingsViewController via didMoveToParentViewController: that you have created this hierarchy. Then you should be able to access the parentViewController.

(Note: this is for iOS 5 only, if you're still on iOS 4 see rob mayoff's reply)

Upvotes: 1

rob mayoff
rob mayoff

Reputation: 386018

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];

Upvotes: 2

Related Questions