开发者

Accessing functions in a parent controller

开发者 https://www.devze.com 2022-12-26 18:26 出处:网络
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?

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 (nes开发者_C百科ted) 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?


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号