views:

149

answers:

2

Ola Folks,

In an iPhone application I am displaying different views by using the addSubView:SomeViewController.view method.

I want to be able to, at the very least, log the view controllers that are in the view hierarchy that is being displayed. I would prefer to be able to get a handle to a specific view controller.

I know how to iterate the views, I just do not see how to access the view controllers of those views. I am looking for something that will give me the type of access to the view controllers that UINavigationController::ViewControllers does.

I thought I could get away with:

for (UIViewController* oVC in [self.view subviews])

but this is not having the intended effect.

If someone has a way of doing this, please share it with me.

-isdi-

+1  A: 

A view doesn't keep a reference to its view controller (or know anything about view controllers in general), so you'll have to keep track of that mapping yourself. If you keep all of your view controllers in an array viewControllers, you could do something like:

- (UIViewController *) viewControllerForView:(UIView *)view {
    for (UIViewController *viewController in viewControllers)
        if (viewController.view == view)
            return viewController;
    return nil;
}
Tom
Ola Tom. Dang. I was hoping this was not the case after half a day trying different methods. Thank you for the answer, I'll implement some sort of tracking mechanism in the RootViewController.
ISDi
A: 

The standard way for a view to interact with the view controller that owns it is by having the view controller set as the delegate or action target of the view. The view is designed not to have any details about the delegate or action target.

If you have implemented your own view, just add a member to hold a reference to the view controller. Or adopt a delegate model for the view so that it does not matter what class the delegate is.

If you are treating the views as a stack and want to maintain a stack of view controllers along side it, similar to what UINavigationController does for you, you must do so manually. Couple every call of addSubview:viewController.view with a call to [myViewControllerArray addObject:viewController] and remove the viewController form the array when the view is removed from the view hierarchy.

drawnonward
Hello Drawnonward,I had not thought of setting the ViewController as the delegate. I like this idea. Thanx. If I could give you a point or something, I would.
ISDi