TabBarController didSelectViewController not working

…衆ロ難τιáo~ 提交于 2020-01-14 09:31:45

问题


I know this is a very repeat topic, but I can't get it works.

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);

}

I can't find what I'm missing, any help will be appreciated.

Now I try to link it into MainStoryBoard:

But it doesnt work, what are the connection?


回答1:


On the basis of your @interface (and your subsequent screen snapshot), MainTab is the UITabBarController, so the following line:

self.tabBarController.delegate = (id)self;

Should just be:

self.delegate = self;

You don't want a tabBarController property in the UITabBarController, itself, nor do you want to use the self.tabBarController syntax. You only use that syntax if you're trying to reference the tab bar controller from one of its children controllers. When in the tab bar controller itself, just refer to self.


Thus, it work if MainBar is defined as:

//  MainBar.h

#import <UIKit/UIKit.h>

@interface MainBar : UITabBarController

@end

And

//  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

And don't forget to set the class of the tab bar controller:

The connections inspector (where I didn't touch a thing) looks like:



来源:https://stackoverflow.com/questions/13707207/tabbarcontroller-didselectviewcontroller-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!