1

似乎UITabBarController不應該被子類化。你會如何推薦我在可旋轉的DetailView中實現TabBarController?替代子類化UITabBarController

謝謝!

+0

爲什麼你需要子類?爲什麼不使用標準標籤欄。在任何情況下[Composition](http://en.wikipedia.org/wiki/Object_composition)都可以替代繼承。 – beryllium 2012-02-21 08:26:13

回答

2

您可以將委託添加到您的控制器<UITabBarDelegate>

創建的TabBar編程

UITabBar * aTabBar;

UITabBarItems 填充它,然後實現這個功能來處理選項卡上的觸摸切換視圖

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item 
{ 
} 

這是代碼的簡要部分

@interface yourTabsViewController : UIViewController <UITabBarDelegate> 
{ 
    UITabBar * mTabBar; 
    NSMutableDictionary * mControllerPerTab; 
} 
@end 

在您的實現:

- (void)viewDidLoad 
{ 
    mControllerPerTab = [[NSMutableDictionary alloc] init]; 
    [mControllerPerTab setValue:controller forKey:@"aKey"]; 
     UIImage *bImage = /*icon of tab*/; 
     UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"title" image:bImage tag:/*a tag for your tab*/]; 
     [tabBarItems addObject:item]; 
    } 

    mTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 49/*tabbbar lenght*/ - 44/*navigationbar length if it exists*/, self.view.bounds.size.width ,49)]; 
    [mTabBar setItems:tabBarItems]; 
    mTabBar.delegate = self; 
    mTabBar.selectedItem = [tabBarItems objectAtIndex:0]; 
    [self tabBar:mTabBar didSelectItem:[tabBarItems objectAtIndex:0]]; 
    // Finally, add the tab controller view to the parent view 
    [self.view addSubview:mTabBar]; 
    [super viewDidLoad]; 
} 

然後你添加這個m方法來處理標籤的切換

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item 
{ 
    int tag = [item tag]; 

    /*I'm using the tag to identify wich coltroller to open*/ 
    UIViewController * controller = [mControllerPerTab objectForKey:[NSString stringWithFormat:@"%d", tag]]; 
    controller.view.frame = CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height - 49); 
    [self.view addSubview:controller.view]; 
    [self.view addSubview:mTabBar]; 
    [self.view autoresizesSubviews]; 
} 
+0

我正在使用故事板,並且無法以編程方式創建選項卡欄,因爲我沒有細分視圖的子類。難道它不能在Storyboard中完成嗎? – AlexR 2012-02-21 08:40:04

+0

我不是很高級的使用故事板,但我認爲你應該做的是專注於添加一個tabBar到你的視圖,並忘記tabBarController,因爲不僅你不能繼承它,但它只能是第一個控制器在你的應用。所以嘗試添加tabBar並在你的代碼中添加委託和切換功能 – 2012-02-21 08:45:51

+0

好吧,你是否願意處理旋轉(BarButtonItem添加和刪除到tabbarcontroller或每個視圖控制器中的工具欄? – AlexR 2012-02-21 08:55:20