我想知道是否有办法向我现有的UITabBarItem
添加额外的UITabBarController
。它不需要在运行时。
我想要做的就是当我按下这个按钮时,我想presentModalViewController:
覆盖我实际可见的ViewController,它应该是TabBarController或它的控制器。
希望这很清楚,如果没有,请随意提问。
答案 0 :(得分:2)
根据我的研究,您无法将UITabBarItem添加到由UITabBarController管理的UITabBar。
由于您可能通过添加视图控制器列表添加了UITabBarItem,这也是您选择添加其他自定义UITabBarItem的方式,我现在将展示:
<强>预条件:强> 正如我之前提到的,您可能通过添加视图控制器列表添加了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;
}
}
现在您已经拥有了创建和处理自定义UITabBarItem所需的一切。 希望这可以帮助。 玩得开心....
答案 1 :(得分:0)