So I have a UIViewController
that has a UITabBar
in the view. I want to pull down JSON and decided what tabs I want to add to the tab bar, so I need to be able to choose the tabs on runtime. I wanted to use the UITabBarController setViewControllers:animated:
method to add to it a list of view controllers. However since I am doing this in a view controller I do not know how to gain access to the tab bar's view controller. Here is my code ...
Header
#import <UIKit/UIKit.h>
@interface HealthTicketTabController : UIViewController <UITabBarDelegate, UITabBarControllerDelegate> {
NSArray *viewControllers;
IBOutlet UITabBar *tabBar;
UIViewController *selectedViewController;
// How do I link this the the tabBar's view controller???
UITabBarController *tabBarController;
}
@property (nonatomic, retain) NSArray *viewControllers;
@property (nonatomic, retain) IBOutlet UITabBar *tabBar;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@property (nonatomic, retain) UIViewController *selectedViewController;
@end
Source
- (id)init
{
self = [super initWithNibName:@"HealthTicketTabView" bundle:nil];
if (self)
{
//Controllers for the tab view
HealthCardController *card = [[HealthCardController alloc] init];
MedicalExpensesController *medical = [[MedicalExpensesController alloc] init];
//Tab bar items to be displayed in the tab bar
card.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:0];
medical.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1];
NSArray *array = [[NSArray alloc] initWithObjects:card, medical, nil];
//Set the tab bar's view controllers to the list
tabBarController.viewControllers = [NSArray arrayWithObjects:card, medical, nil];
[array release];
[card release];
[medical release];
}
return self;
}
UIViewController has a tabBarController property already. You do not need one in your header file. This is how you can access the UITabBarController.
Found out that since I was using a UIViewController
to control the UITabBar
I need to set the tab bar's delegate to the current UIViewController
and handle the tab events in the current controller.
Adding TabBarItems to the TabBar
[self.tabBar setItems: tabBarItems animated:TRUE];
Switching between ViewControllers
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
UIViewController *temp = [viewControllers objectAtIndex:item.tag];
[self.selectedViewController.view removeFromSuperview];
[self.view addSubview:temp.view];
self.selectedViewController = temp;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.