2012-10-23 143 views
1

UITabBarController中,選擇選項卡後,我希望該選項卡的UIViewController更改(分配新的viewcontroller)。我試試這個 -更改UITabBarController的視圖控制器

NSMutableArray *tabBarViewControllers = [myUITabBarController.viewControllers mutableCopy]; 
[tabbarViewControllers replaceObjectAtIndex:0 withObject:[[myViewcontroller1 alloc] init]]; 
[myUITabBarController setViewControllers:tabbarViewControllers]; 

但它給出了錯誤。如何分配新的UIViewController並立即刷新?

回答

2

請參閱此代碼,它提供了2個帶導航的tabbar。 在AppDelegate.h請聲明

UINavigationController *nav1; 
    UINavigationController *nav2; 
    UITabBarController *tab; 

而在Appdelegate.m,在didFinishLaunchingWithOptions請加: -

tab = [[UITabBarController alloc]init]; 

    ViewController *view1 = [[ViewController alloc]init]; 

    nav1= [[UINavigationController alloc]initWithRootViewController:view1];  
    UITabBarItem *tab1 = [[UITabBarItem alloc]initWithTitle:@"Add" image:[UIImage imageNamed:@"Plus.png"] tag:1]; 
    view1.title = @"Add"; 
    [view1 setTabBarItem:tab1]; 

    SettingsViewController *view2 = [[SettingsViewController alloc]init]; 

    nav2= [[UINavigationController alloc]initWithRootViewController:view2]; 
    UITabBarItem *tab2 = [[UITabBarItem alloc]initWithTitle:@"Setting" image:[UIImage imageNamed:@"settings.png"] tag:2]; 
    view2.title = @"Setting"; 
    [view2 setTabBarItem:tab2]; 

    tab.viewControllers = [NSArray arrayWithObjects:nav1,nav2,nil]; 

    self.window.backgroundColor = [UIColor whiteColor]; 
    self.window.rootViewController = tab; 

還要檢查這個環節進一步落實......希望這有助於:)

UItabBar changing View Controllers

+0

謝謝!但我可以做到沒有導航控制器? – user1559227

0

AppDelegate.h

UIViewController *vc1; 
UIViewController *vc2; 
UIViewController *vc3; 
Appdelegate.m

didFinishLaunchingWithOptions

NSMutableArray *listOfViewControllers = [[NSMutableArray alloc] init]; 

vc1 = [[UIViewController alloc] init]; 
vc1.title = @"A"; 
[listOfViewControllers addObject:vc1]; 

vc2 = [[UIViewController alloc] init]; 
vc2.title = @"B"; 
[listOfViewControllers addObject:vc2]; 

vc3 = [[UIViewController alloc] init]; 
vc3.title = @"C"; 
[listOfViewControllers addObject:vc3]; 

[self.tabBarController setViewControllers:listOfViewControllers 
           animated:YES]; 
0

這是基於費米那獎的答案,但不要求你建立視圖控制器全陣列,它只是讓你更換與另一個現有的視圖控制器。在我來說,我想在一個不同的XIB文件交換的iPhone 5屏幕:

if ([[UIScreen mainScreen] bounds].size.height == 568) { 
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers]; 
    Tracking *tracking568h = [[Tracking alloc] initWithNibName:@"Tracking-568h" bundle:nil]; 
    tracking568h.title = [[viewControllers objectAtIndex:0] title]; 
    tracking568h.tabBarItem = [[viewControllers objectAtIndex:0] tabBarItem]; 
    [viewControllers replaceObjectAtIndex:0 withObject:tracking568h]; 
    [tracking568h release]; 
    [self.tabBarController setViewControllers:viewControllers animated:FALSE]; 
} 

這改變了第一個選項卡視圖控制器,保持相同的標籤圖標和標籤。

相關問題