views:

226

answers:

3

I have made a ViewController in XCode for an iPhone project I'm working on, but I have a question about nested ViewControllers and what the best way to access a parents ViewController functions?

Essentially, at the moment I have a SwitchViewController with MenuViewController (nested) and GameViewController (nested, which renders OpenGL ES).

At the moment, I have animated view switching controlled in the SwitchViewController which works. But I want to call it after a player has selected the level from the MenuViewController and run the appropriate level in GameViewController. Not rocket science, I know.

What's the best way to call parent functions?

+1  A: 

You'd have to create a pointer to the view controllers parent, and set it when you nest the view controller's view in another view.

Jasarien
+1  A: 

I'm not sure if I understand you question correctly, but I would go with the delegate pattern. Pass the pointer to the parent view controller as a delegate to the nested view controller - this allows you to call the delegate's methods on the parent class from the nested one.

Jakub
A: 

I have worked it out and wanted to share my findings.

In a subview or subviewcontroller you can use the following code as a pointer to other places.

#import "TwoViewAppDelegate.h" // import the header of the class you want to reference


- (IBAction)setRedColor:(id)sender
{
    // Use the class name and create a pointer (in this case mainDelegate)
    TwoViewAppDelegate *mainDelegate = (TwoViewAppDelegate *)[[UIApplication sharedApplication] delegate];
    mainDelegate.textColor = [UIColor redColor];
    [mainDelegate flipToFront];
}
meridimus