简体   繁体   English

每次从标签栏按下标签时,如何执行方法?

[英]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 如果你正在使用的Xcode 4.2.x版则模板建立UITabBarController在代码中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 右键单击对象视图中的Tab bar controller
  2. Locate the delegate outlet 找到delegate插座
  3. Connect the delegate outlet to the File's Owner 该连接delegate出口到File's Owner

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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