views:

440

answers:

1

Hello!

I have a TabBar in my application and I do this in my AppDelegate:

...
test2ViewController = [[Test1ViewController alloc] init];
...
navigationTest2Controller = [[UINavigationController alloc] initWithRootViewController:test2ViewController];

NSArray *myControllers = [NSArray arrayWithObjects:..., navigationTest2Controller, nil];
[self.myTabBarController setViewControllers:myControllers animated:NO];

Now I have the problem that I am in a ViewController and I want to switch to the "navigationTest2Controller". I do this in my AppDelegate with:

self.myTabBarController.selectedViewController = navigationTest2Controller;

This works. It switches to this ViewController! This ViewController was already loaded and the viewDidLoad method was called. In this viewDidLoad method is a methos call:

[self myMethod];

I want, that if the view switches to this ViewController this "myMethod" should always be called. How can I do this? In my AppDelegate before the line

self.myTabBarController.selectedViewController = navigationTest2Controller;

??? Or is there another delegate which will be called every time the ViewController is selected/switched to?

Does anyone know this?

Thanks a lot in advance & Best Regards.

+2  A: 

You should place any code that you want to run when the view becomes visible in the -viewWillAppear: or -viewDidAppear method of your view controller.

EDIT: To make this happen only when you switch from a certain view, you can subclass UITabBarController, only modifying the –tabBarController:shouldSelectViewController: method. In that method, you could do something like this:

- (BOOL)tabBarController:(UITabBarController *)tabBarController
shouldSelectViewController:(UIViewController *)viewController
{
    if (self.selectedIndex == 1 &&
        [viewController respondsToSelector:@selector(myMethod)]) {
        [viewController myMethod];
    }

    return YES;
}
Jeff Kelley
But I only want to call this "myMethod" if I switch from the specific ViewController to this one. All other times, this method should not be called.
Tim
Tim, I've updated the answer with something that might be more what you're looking for.
Jeff Kelley
Thanks a lot for your help!
Tim