根据我的研究,您无法将 UITabBarItem 添加到由 UITabBarController 管理的 UITabBar。
由于您可能通过添加视图控制器列表添加了您的 UITabBarItem,这也是您选择添加更多自定义 UITabBarItems 的方式,我现在将展示:
前提条件:
正如我之前提到的,您可能已经通过添加视图控制器列表来添加您的 UITabBarItems:
tabbarController = [[UITabBarController alloc] init]; // tabbarController has to be defined in your header file
FirstViewController *vc1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:[NSBundle mainBundle]];
vc1.tabBarItem.title = @"First View Controller"; // Let the controller manage the UITabBarItem
SecondViewController *vc2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];
vc2.tabBarItem.title = @"Second View Controller";
[tabbarController setViewControllers:[NSArray arrayWithObjects: vc1, vc2, nil]];
tabbarController.delegate = self; // do not forget to delegate events to our appdelegate
添加自定义UITabBarItems:
既然你知道如何通过添加视图控制器来添加UITabBarItems,你也可以使用相同的方式添加自定义UITabBarItems:
UIViewController *tmpController = [[UIViewController alloc] init];
tmpController.tabBarItem.title = @"Custom TabBar Item";
// You could also add your custom image:
// tmpController.tabBarItem.image = [UIImage alloc];
// Define a custom tag (integers or enums only), so you can identify when it gets tapped:
tmpController.tabBarItem.tag = 1;
修改上面的行:
[tabbarController setViewControllers:[NSArray arrayWithObjects: vc1, vc2, tmpController, nil]];
[tmpController release]; // do not forget to release the tmpController after adding to the list
很好,现在您的 TabBar 中有自定义按钮。
如何处理这个自定义 UITabBarItem 的事件?
很简单,看:
将 UITabBarControllerDelegate 添加到您的 AppDelegate 类(或持有 tabbarController 的类)。
@interface YourAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { }
通过添加此函数来适应协议定义:
- (void)tabBarController:(UITabBarController *)theTabBarController didSelectViewController:(UIViewController *)viewController {
NSUInteger indexOfTab = [theTabBarController.viewControllers indexOfObject:viewController];
UITabBarItem *item = [theTabBarController.tabBar.items objectAtIndex:indexOfTab];
NSLog(@"Tab index = %u (%u), itemtag: %d", indexOfTab, item.tag);
switch (item.tag) {
case 1:
// Do your stuff
break;
default:
break;
}
}
现在您拥有创建和处理自定义 UITabBarItems 所需的一切。希望这可以帮助。玩得开心....