1

I am wondering if there is a way to add an additional UITabBarItem to my exisiting UITabBarController. It doesn't need to be in runtime.

All I want to do is when hitting this button I want to presentModalViewController: over my actually visible ViewController, which should either be the TabBarController or its controllers.

Hopefully this is clear enough, if not, feel free to ask.

4

2 回答 2

2

根据我的研究,您无法将 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 所需的一切。希望这可以帮助。玩得开心....

于 2011-05-06T08:36:09.427 回答
0

访问 UITabBarController ( reference )的 tabBar - 属性,使用 - 属性 ( itemsreference )获取元素数组,将新的 UITabBarItem 添加到此数组并使用 tabBar 的setItems:animated:- 方法更新标签栏。向此选项卡栏添加一个操作以显示模态视图控制器。

于 2011-01-29T12:27:55.087 回答