Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabBarController didSelectViewController not working

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:

enter image description here

enter image description here

But it doesnt work, what are the connection?

like image 518
user1256477 Avatar asked Dec 04 '12 16:12

user1256477


1 Answers

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:

interface builder

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

outlets

like image 179
Rob Avatar answered Oct 07 '22 14:10

Rob