2011-12-27 151 views
0

因此,我有一個UIViewController,該視圖中有UITabBar。我想拉下JSON並決定要將哪些標籤添加到標籤欄,因此我需要能夠在運行時選擇標籤。我想用UITabBarController setViewControllers:animated:方法添加一個視圖控制器列表。然而,因爲我在視圖控制器中這樣做,我不知道如何訪問標籤欄的視圖控制器。這裏是我的代碼...將UITabBarItem添加到UIViewController中的UITabBar中

#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 

來源

- (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; 
} 

回答

1

發現,因爲我使用的是UIViewController來控制UITabBar我需要將標籤欄的代理設置爲當前的UIViewController並處理當前控制器中的標籤事件。

添加TabBarItems的TabBar

[self.tabBar setItems: tabBarItems animated:TRUE]; 

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; 
} 
1

的UIViewController有tabBarController財產了。你的頭文件中不需要一個。這是你如何訪問UITabBarController。