UITabBarDelegate in AppDelegate
I have a UITabController in my main window, and would like to add some logic when each tab is selected. I've added the delegate to the header file:
@interface MyAppAppDelegate : NSObject <UIApplicationDelegate, UITabBarDelegate> {
I have a method for the tab change event:
- (void)tabBar:(UITabBa开发者_运维百科r *)tabBar didSelectItem:(UITabBarItem *)item{
//some code
}
But the code inside the didSelectItem method isn't called. I've connected the delegate for the UITabBarController to my AppDelegate in IB. Is there anything else I need to do?
If you assign the delegate via IB, you should connect the delegate for your TabBar (as opposed to your TabBarController) to your app delegate.
Indeed, you are not looking for the UITabBarControllerDelegate
, but for the UITabBarDelegate
.
If you do it programmatically, then, from your tab bar controller viewDidLoad
execute:
self.tabBar.delegate = [UIApplication sharedApplication].delegate;
If you use UITabbarController
you can use UITabBarControllerDelegate
instead of UITabBarDelegate
.
Then, you can set self.delegate = self
. Then you use:
(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
instead of:
(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;
Did you assign some class to be the tab bar's delegate? Something like
myTabBar.delegate = self;
i might be out on a ledge here but i think the signature of the method should be:
- (IBAction)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
and then you connect it to the tabbar in IB. after you change to IBAction it should appear in IB
I ended up putting it in the viewWillAppear method of the view in the specific tab I need. Seems to work fine.
精彩评论