簡體   English   中英

將UITabBarItem添加到UIViewController中的UITabBar

[英]Adding UITabBarItem to a UITabBar in a UIViewController

所以我有一個UIViewController在視圖中有一個UITabBar 我想下拉JSON並確定我想要添加到選項卡欄的選項卡,所以我需要能夠在運行時選擇選項卡。 我想使用UITabBarController setViewControllers:animated:方法向其中添加一個視圖控制器列表。 但是,由於我在視圖控制器中執行此操作,因此我不知道如何訪問選項卡欄的視圖控制器。 這是我的代碼......

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

UIViewController已經有一個tabBarController屬性。 您的頭文件中不需要一個。 這是您可以訪問UITabBarController的方法。

發現由於我使用UIViewController來控制UITabBar我需要將標簽欄的委托設置為當前的UIViewController並處理當前控制器中的tab事件。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM