我想在有人在选项卡之间切换时捕获事件。我的 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");
永远不会触发。 xcode 对 uitbc.delegate = self;
行发出警告,表示“将 appdelegate const__strong 传递给不兼容类型 id 的参数”。
我做错了什么?我只是按照此处找到的已接受答案进行操作,除了我正在实例化我的 tabbarcontroller 表单 Storyboard:
how to get the event that switch tab menu on 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 仍然没有触发。
最佳答案
在我的 appdelegate.h 文件中,我更改了行
@interface wscAppDelegate : UIResponder <UIApplicationDelegate>
到
@interface wscAppDelegate : UIResponder <UIApplicationDelegate,UITabBarControllerDelegate>
然后在我的 CustomTabBarController 的 viewDidLoad 函数中,我添加了这些行:
wscAppDelegate *appDelegate = (wscAppDelegate *)[[UIApplication sharedApplication] delegate];
self.delegate = appDelegate;
然后在appdelegate.m文件中,我添加了这个函数
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSLog(@"hooray this works");
}
关于objective-c - 如何实现 didSelectViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891182/