0

Firstly, I have set both viewcontrollers to be UITabBarController delegates. Both are part of a tab bar controller. I did this by putting the following code into each viewDidLoad:

self.tabBarController.delegate = self;

Then I added the following delegate method to CalculatorsViewController:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
[self presentCalculatorsView];
}

Where presentCalculators view simply reveals a subview within the same view controller.

I also added the following delegate method to the OptionsViewController:

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    [self presentHomeScreen];

}

Again this method simply reveals another subview within the viewController.

The problem I am having is that the OptionsViewController presentHomeScreen method is only called if I do not visit the CalculatorsViewController. Once I do visit the CalculatorsViewController in the app and then return to OptionsViewController,

[self presentHomeScreen]

is never called. In fact, it appears that it still calls the method from the CalculatorsViewController. I tested it with an NSLog statement.

Any ideas why one method overrides the other? Or why the tab bar button executes code from another viewController, other than the one that is active?

EDIT* It is almost as if the one viewController 'steals' the delegate from the other.

4

1 回答 1

1

By calling self.tabBarController.delegate = self; on each viewDidLoad method, you are basically telling the tab bar controller to use abandon the current delegate and use the current view controller as delegate.

Note that the viewDidLoad method is called only once under normal circumstances. (It may be called again when the view of your view controller is unloaded due to memory warning, for example, then you access the view of your view controller again, which calls loadView/awakeFromNib and viewDidLoad. I'm not entirely sure on this scenario though.) In your scenario:

  1. Open OptionsViewController for the first time - tab bar controller's delegate is OptionsViewController
  2. Open CalculatorsViewController for the first time - tab bar controller's delegate is now CalculatorsViewController
  3. Go back to OptionsViewController - tab bar controller's delegate is still CalculatorsViewController, as the viewDidLoad is not called again

If you must change the delegate, you can do it instead in the viewWillAppear method.

于 2012-10-17T03:40:38.140 回答