当标签栏点击时,转到根视图

时间:2012-08-27 13:17:57

标签: iphone objective-c ios xcode uitabbarcontroller

我使用了基于视图的应用程序&在那我以编程方式生成TabBar。 问题是:

我有一个Iphone应用程序,其中我有两个tabitems与tabbarcontroller.Inside tabbarcontroller每个viewcontroller是一个导航控制器。当选择第二个选项卡我有一个视图控制器。当选择一个按钮,我正在推另一个视图控制器到self.navigation控制器。在那个viewcontroller中,我正在推,然后去那样。但问题是当我再次选择tabitem时,pushviewcotrooller会显示在那里。但是当我选择选项卡时,我再次需要rootview

我在AppDelegate.m中的代码是:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

 UINavigationController *nc1;
    nc1 = [[UINavigationController alloc] init];

UIViewController *viewController1 = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    nc1.viewControllers = [NSArray arrayWithObjects:viewController1, nil];





    UINavigationController *nc2;
    nc2 = [[UINavigationController alloc] init];

 UIViewController *viewController2 = [[[secondview alloc] initWithNibName:@"secondview" bundle:nil] autorelease];
    nc2.viewControllers = [NSArray arrayWithObjects:viewController2, nil];


    self.tabBarController = [[[UITabBarController alloc] init] autorelease];
   self.tabBarController.viewControllers = [NSArray arrayWithObjects:nc1,nc2,nil];
  self.window.rootViewController=self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

4 个答案:

答案 0 :(得分:12)

可能你正在寻找这个:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{       
    int tabitem = tabBarController.selectedIndex;
    [[tabBarController.viewControllers objectAtIndex:tabitem] popToRootViewControllerAnimated:YES];
}

答案 1 :(得分:3)

在swift中你可以在UITabBarController课程中这样做:

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    let rootView = self.viewControllers![self.selectedIndex] as! UINavigationController
    rootView.popToRootViewControllerAnimated(false)
}

答案 2 :(得分:0)

我相信你需要采用这两种方法:

UINavigationController: - popToRootViewControllerAnimated

UITabBarControllerDelegate: tabBarController:didSelectViewController:

我在自己的程序中使用的方法是仅在屏幕上显示根视图控制器时显示标签栏。

答案 3 :(得分:0)

UITabBarControllerDelegate添加到您的AppDelegate,并在didFinishLaunchingWithOptions方法中将代理设置为UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController; tabBarController.delegate = self;。然后,当选择tabbar时,将调用委托方法- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController