iPhone - calling a method in parent view controller
have hunted around for an answer to this one, but can't seem to find a definitive solution - hoping someone can help here!
I'm building a multiview app for the iPhone. I've created a UIViewController called "MainViewController", which loads in other views as required. There's q开发者_运维技巧uite a lot of navigation between screens, so what I'd like to do is have a "ViewSwitcher" method in MainViewController that the child view controllers can call to ask for the view to switch away to another child view.
How can I call the "ViewSwitcher" method from the child controllers? I've managed to achieve this at present by creating an UIView *"parent" property in each child view controller, and populating this on first loading the child view. I can then call the method using [parent ViewSwitcher]. This seems a bit clunky, and I'm concerned I'm creating some horribly recursive structure. Is there a better way?
Thanks in advance.
Here's something that looks clunky, but it should demonstrate the general idea:
NSArray *viewControllerArray = [self.navigationController viewControllers];
int parentViewControllerIndex = [viewControllerArray count] - 2;
[[viewControllerArray objectAtIndex:parentViewControllerIndex] setBackBarButtonItemTitle:@"New Title"];
Much of this can easily be replaced with a #define
macro:
#define CurrentParentViewController [[self.navigationController viewControllers] objectAtIndex:[[self.navigationController viewControllers] count] - 2]
You might then use it as follows:
[CurrentParentViewController setBackBarButtonItemTitle:@"New Title"];
This would obviously crash and burn if you call this at the bottom-most view controller in the navigation stack, but presumably you would know when you're using this approach. You could, for example, call [[self.navigationController viewControllers] count]
to make sure you can run this.
You could create a singleton object. This cocoawithlove article does a magnificent job on this topic.
精彩评论