如果您在 IB 中选择您的 UITabBarItems 之一,您将看到“从“YourView”加载的视图”。点击进入这个“灰色”视图。在 Inspector 窗口中,您将在 Attributes 选项卡(左侧的选项卡)中看到标题和将加载的 NIB 名称(我们称之为“YourNibName”)。
现在选择检查器的右侧选项卡(身份)并将类名(类旁边的组合)更改为您必须在 xcode 中创建的“YourViewController”类。不要使用已经选择的标准 ViewController。 InterfaceBuilder 加载您的 nib 并将其附加到您的 ViewController。
打开 YourNibName 并将 FilesOwner 的 Class(Inspector,右选项卡)也更改为“YourViewController”。
您的 TabBar 的 NIB 也包含一个 FilesOwner。为这个 FilesOwner 创建一个 ViewController 并将它的 Class 设置为这个 Controller(即 TabBarController)
在“TabBarController”中,您可以使用以下代码找出选择了哪个选项卡:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
if ([viewController.nibName isEqualToString:@"NIBName1"]){
// Do something here, if you like. (i.e. Save the state in a string or int)
}
if ([viewController.nibName isEqualToString:@"NIBNAme2"]){
// Do something here, if you like. (i.e. Save the state in a string or int)
}
...
}
在这里你可以做一些“全局”的事情或预初始化一些事情。这是您可以做的一件事。
你的观点的初始:
如果你选择一个Tab并且第一次显示视图(由YourViewController处理),“viewDidLoad”将在“YourViewController”中调用
- (void)viewDidLoad {
// Here you can add views programatically
[self.view addSubview:myNavigationController.view];
[self.view bringSubviewToFront:myNavigationController.view];
// And if you like, do some INIT here
[super viewDidLoad];
}
我希望这就是你的问题。
现在关于徽章的事情。这是一个 hack,但对我来说效果很好。
头文件:
向你的控制器添加一个出口,它代表你的 TabBarController:
@interface yourController : UIViewController <UITabBarControllerDelegate> {
UITabBarController *tabBarController;
}
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@end
将 IB 中的此插座与您的 TabBar 连接。
实施:
在您的 TabBarControllerClass 中,您可以覆盖“initWithNibName”:
@synthesize tabBarController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Do some init here
// select your desired item (it will be loaded)
// then you can assign the badge
tabBarController.selectedIndex = 1;
tabBarController.selectedViewController.tabBarItem.badgeValue = @"222";
// and select the item you will start with
tabBarController.selectedIndex = 0;
// if you like you can add a notification, which you can activate from anywhere else
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(itemBadgeChanged:)
name:@"itemBadgeChangedNotification"
object:nil];
}
return self;
}
如果您不使用 nib,请改用 '- (void)loadView { ... }'。
您正在使用 TabBar 控制器的子类,也许您可以使用 'self.selectedIndex = 1;'而不是 'tabBarController.selectedIndex = 1;' 等等。试试这个
希望这会有所帮助!