3

当有人在标签之间切换时,我想捕捉事件。我的 appdelegate 文件中有以下两个函数:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UITabBarController * uitbc = [storyboard instantiateViewControllerWithIdentifier:@"tabbarcontroller"];
    uitbc.delegate = self;
    [self.window addSubview:uitbc.view];

    return YES;
}


- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    NSLog(@"switching");
}

NSLog(@"switching");永远不会开火。uitbc.delegate = self;xcode 对“将 appdelegate const__strong 传递给不兼容类型 id 的参数”这一行发出警告。

我究竟做错了什么?我只是按照此处找到的公认答案,除了我正在实例化我的 tabbarcontroller 表单故事板:

如何获取在iphone上切换标签菜单的事件

更新 根据 skram 的建议,我为我的 appdelegate 写了这个,但 NSLOG(Switching) 仍然没有触发:

@interface johnAppDelegate : UIResponder <UITabBarControllerDelegate>

我还更新了我的 didFinishLauchingWithOptions:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
tabBarController = self.window.rootViewController.tabBarController;
tabBarController.delegate = self;
[window addSubview:tabBarController.view];
}

好在没有崩溃。我也不再发出关于不兼容类型的警告。但是,didSelectViewController 仍然没有触发。

4

3 回答 3

4

在我的 appdelegate.h 文件中,我更改了行

@interface wscAppDelegate : UIResponder <UIApplicationDelegate>

@interface wscAppDelegate : UIResponder <UIApplicationDelegate,UITabBarControllerDelegate>

然后在 viewDidLoad 函数的 CustomTabBarController 中,我添加了以下几行:

wscAppDelegate *appDelegate = (wscAppDelegate *)[[UIApplication sharedApplication] delegate];
self.delegate = appDelegate;

然后在 appdelegate.m 文件中,我添加了这个函数

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

NSLog(@"hooray this works");

}
于 2012-06-06T00:45:17.720 回答
2

我也为此苦苦挣扎,但我的 UITabBarNavigationController 离 AppDelegate 设置它还很远,真正使它工作的唯一方法不是在 UITabBarController 子类本身的 viewDidLoad 中执行它,而是在它的:

-(void)viewDidLayoutSubviews {
    [ super viewDidLayoutSubviews ];
    self.delegate = self;
}

这解决了它。或者,您可以在任何选项卡栏控制的视图控制器中执行此操作,但这感觉不对。

于 2013-10-07T07:39:43.587 回答
0

您需要您的 AppDelegate 符合UITabBarControllerDelegate协议。见下文..

@interface YourAppDelegate : UIResponder <UITabBarControllerDelegate>
于 2012-06-05T03:40:12.567 回答