点击tabBar时转到rootView
我用基于视图的应用程序&在我编程生成TabBar。 问题是:
我有一个Iphone应用程序,其中我有两个tabitems与tabbarcontroller.Inside tabbarcontroller每个viewcontroller是一个导航controller.whenselect第二个选项卡我有一个视图controller.whenselect一个button,我推另一个视图控制器到self.navigation controller.and在该视图控制器我推,并去那样。但问题是,当我selecttabitem再次pushviewcotrooller显示在那里。但我需要那个rootview那里再次当我select选项卡
我在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; }
可能是你正在寻找这个:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { int tabitem = tabBarController.selectedIndex; [[tabBarController.viewControllers objectAtIndex:tabitem] popToRootViewControllerAnimated:YES]; }
在swift中,你可以在你的UITabBarController
类中这样做:
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { let rootView = self.viewControllers![self.selectedIndex] as! UINavigationController rootView.popToRootViewControllerAnimated(false) }
我相信你将需要使用这两种方法:
UINavigationController
: – popToRootViewControllerAnimated
:
UITabBarControllerDelegate: tabBarController:didSelectViewController:
我在自己的程序中使用的方法是只在屏幕上显示根视图控制器时显示标签栏。
将UITabBarControllerDelegate
添加到你的AppDelegate
,并在didFinishLaunchingWithOptions
方法,设置委托像UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController; tabBarController.delegate = self;
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController; tabBarController.delegate = self;
。 然后委托方法- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
将在selecttabbar时被调用。
在Swift 3.1中
将UITabBarControllerDelegate
添加到您的TabBar类:
class YourClass: UITabBarController, UITabBarControllerDelegate {
后:
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController yourView .popToRootViewControllerAnimated(false) }