2012-10-23 103 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]; 
} 

这改变了第一个选项卡视图控制器,保持相同的标签图标和标签。

相关问题