TabBarController didSelectViewController不起作用

我知道这是一个非常重复的话题,但我无法得到它的工作。

MainTab.h:

#import <UIKit/UIKit.h> @interface MainTab : UITabBarController<UITabBarControllerDelegate, UITabBarDelegate> { IBOutlet UITabBarController *tabController; } @property (nonatomic,retain) IBOutlet UITabBarController *tabController; @end 

MainTab.m

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { NSLog(@"main tab"); [super viewDidLoad]; self.tabBarController.delegate = (id)self; [self setDelegate:self]; // Do any additional setup after loading the view. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. } -(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { NSLog(@"selected %d",tabBarController.selectedIndex); } 

我找不到我想要的,任何帮助将不胜感激。

现在我尝试将它链接到MainStoryBoard:

在这里输入图像说明

在这里输入图像说明

但它不起作用,连接是什么?

根据你的@interface (和你的后续屏幕快照), MainTabUITabBarController ,所以下面这行:

 self.tabBarController.delegate = (id)self; 

应该是:

 self.delegate = self; 

你不想在UITabBarController本身中使用tabBarController属性,也不想使用self.tabBarController语法。 如果您试图从其子控制器之一引用标签栏控制器,则只能使用该语法。 当在标签栏控制器本身,只是指self


因此,如果MainBar被定义为:

 // MainBar.h #import <UIKit/UIKit.h> @interface MainBar : UITabBarController @end 

 // MainBar.m #import "MainBar.h" @interface MainBar () <UITabBarControllerDelegate> @end @implementation MainBar - (void)viewDidLoad { [super viewDidLoad]; self.delegate = self; } -(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { NSLog(@"selected %d",tabBarController.selectedIndex); } @end 

不要忘记设置标签栏控制器的类:

界面生成器

连接检查员(我没有碰到的东西)看起来像:

网点