问题
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