私の調査の結果、UITabBarControllerによって管理されているUITabBarにUITabBarItemを追加することはできません。
ビューコントローラのリストを追加してUITabBarItemを追加した可能性があるため、これは、次に示すように、さらにカスタムUITabBarItemを追加するための選択方法でもあります。
前提条件:
前に述べたように、ViewControllerのリストを追加して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の追加:
View Controllerを追加して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を作成して処理するために必要なものがすべて揃いました。お役に立てれば。楽しむ....