从另一个选项卡调用popToRootViewController
我有导航控制器应用程序使用故事板标签栏,
我的目的是按tab3中的button,并在后台我想tab1“popToRootViewController”
tab3 viewcontroller中的button:
- (IBAction)Action:(id)sender { vc1 * first = [[vc1 alloc]init]; [first performSelector:@selector(popToRootViewController) withObject:Nil]; }
在tab1 viewcontroller中的代码
-(void)popToRootViewController{ [self.navigationController popToRootViewControllerAnimated:NO]; NSLog(@"popToRootViewController"); }
我在日志中得到了popToRootViewController
,但操作没有执行。
解决问题:
- (IBAction)Action:(id)sender { [[self.tabBarController.viewControllers objectAtIndex:0]popToRootViewControllerAnimated:NO]; }
你这样做的方式:
vc1 * first = [[vc1 alloc]init]; [first performSelector:@selector(popToRootViewController) withObject:Nil];
是不正确的。 事实上,您正在创build一个全新的控制器,完全独立于您现有的控制器,不属于任何导航控制器。 由于这个原因, self.navigationController
在popToRootViewController
是popToRootViewController
。
你可以尝试做如下的事情:
//-- this will give you the left-most controller in your tab bar controller vc1 * first = [self.tabBarController.viewControllers objectAtIndex:0]; [first performSelector:@selector(popToRootViewController) withObject:Nil];
将TabBar与tabBarViewController-
在tabBarViewController.m中
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { NSArray *array = [tabBarController viewControllers]; if([[array objectAtIndex:tabBarController.selectedIndex] isKindOfClass:[UINavigationController class]]) [(UINavigationController *)[array objectAtIndex:tabBarController.selectedIndex] popToRootViewControllerAnimated: NO]; }
它对我来说是完美的。
To press a button in tab3 and in the background I want tab1 to "popToRootViewController"
如果你想在tab1中按下popToRootViewController
中的button来执行popToRootViewController
,那么我想build议使用NSNotificationCenter
。 例如按照下面的代码:
在你的firstViewController
类中添加NSNotification
的观察者
- (void)viewDidLoad { [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(yourMethod:) name:@"popToRootViewControllerNotification" object:nil]; } -(void)yourMethod:(NSNotification*)not { [self.navigationController popToRootViewControllerAnimated:NO]; }
在您的ThirdViewController
类中发布以下代码中的notification
: –
- (IBAction)Action:(id)sender { // vc1 * first = [[vc1 alloc]init]; // [first performSelector:@selector(popToRootViewController) withObject:Nil]; //Post your notification here [[NSNotificationCenter defaultCenter] postNotificationName:@"popToRootViewControllerNotification" object:nil]; }
如果你的tab1和tab2在不同的navigationController中,那么在- (IBAction)action:(id)sender
试试这个- (IBAction)action:(id)sender
NSArray *viewControllers = [self.tabbarController viewControllers]; for (UIViewController *viewController in viewControllers) { if ([viewController isKindOfClass:[vc1 class]]) { vc1 * first = (vc1 *) viewController; [first.navigationController popToRootViewControllerAnimated:NO]; } }