简体   繁体   中英

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:(UITabBar *)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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM