简体   繁体   中英

How do I execute a method every time a tab is pressed from the tab bar?

I want to run a method every time a tab from the tab bar is pressed in my app. How do I do this? I have a tab bar controller in my storyboard (built when i chose tab bar application when I created the project).

For example I want to print 'tab button pressed to the console every time a tab button is pressed.

I tried adding this in the app delegate without any luck:

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{

    NSLog(@"Tab Button Pressed");

}

This is probably quite simple but I'm missing something.

您是否已将视图控制器设置为选项卡栏的委托?

If you are using xcode 4.2.x then the templates set up the UITabBarController in code in the appDelegate

self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.delegate = self;    //<---- Add this line
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
self.window.rootViewController = self.tabBarController;

If you have an old style project or built your structure using interface builder then:

  1. Right click the Tab bar controller in the objects view
  2. Locate the delegate outlet
  3. Connect the delegate outlet to the File's Owner

在此处输入图片说明在此处输入图片说明

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