I have a view that loads a view, that needs to push a view to the main navig开发者_运维百科ation controller.
I've setup a delegate for each view, and basically make my call back up the 'chain' to the main navigation controller.
It works, but I am curious if there is a better (easier?) way to achieve this?
You could use the NSNotificationCenter to send a message that your NavigationController will respond to.
In your view that needs to call the NavigationController, you would write something like:
[[NSNotificationCenter defaultCenter] postNotificationName:@"DoWork" object:nil];
Where @"DoWork"
is the unique (most likely) message name to which another object will respond.
And in your NavigationController you would need to add an observer to be able to catch that notification, like so:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doWork) name:@"DoWork" object:nil];
Where @selector(doWork)
is the selector you want to perform when the notification is posted, and @"DoWork"
is the notification you want to respond to.
So view A loads view B. Later, view B loads view C and wants to push its view controller onto the navigation controller upstream from view B's? view A's? view controller.
Provided view B has a view controller that is part of the navigation stack, then its view controller can grab the navigation controller, no matter how far down the stack it is, via [self navigationController]
.
Views do not have a pointer to their controller, but if you wanted to totally break MVC, you could have the controller set one itself. The better approach would be to have the controller receive the tap action (or whatever it is that prompts loading and pushing view C) and then have the view controller handle the swapping. For example, if view B is a table view, you would set its view controller as the UITableViewDelegate
so that it can handle selection of a row by pushing a new view controller.
Your question seems to indicate that you are not distinguishing between a view, its view controller, a navigation controller, and the view that's being displayed in the navigation controller's content region. All these objects play a different rôle, so it would pay off for you to look more closely at them and their interrelationships before continuing to develop your application.
Depending on how you've set up your program, if your App Delegate contains a UINavigationController
you can access the navigation controller from anywhere:
[[[NSApp delegate] navigationController] pushViewController: myVC animated:YES];
But again, that only works if your app delegate contains a UINavigationController
.
精彩评论