Calling poptoviewcontroller function from a viewcontroller

泪湿孤枕 提交于 2020-01-14 03:09:07

问题


Let me explain clearly.

I have a tabbarcontoller in the viewcontroller which is the main view controller of the single view application project.

I added a tabbarcontroller to the viewcontroller as the subview. In the tabbarcontroller, I added two navigation controllers like below image,

I have added three(named First, Second, Third) more viewcontrollers as new file.

If I navigate from one viewcontroller to other in a tab using below,

third =  [[Third alloc] initWithNibName:@"Third" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:third animated:YES];

If I switch to next tab and come back to the previous tab, it should popto the previous view controller, how to do this?

I tried

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{

    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}

not succeed,

I also tried,

[third popto];

In the third viewcontroller,

-(void)popto
{
  [self.navigationController popViewControllerAnimated:YES];
}

nothing happened.

Now, I have to click the tab again to poptoviewcontroller to the first viewcontroller.

Any ideas will be highly appreciated.


回答1:


Try the below code snippet

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
 UINavigationController *navController = (UINavigationController*)viewController;

if (navController && ([[navController viewControllers] count] > 0))
{
    [navController popToRootViewControllerAnimated:NO];
}
return YES;
}

Hope it may work for you.




回答2:


You should try using

[viewController.navigationController  popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];

instead of

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];



回答3:


How about overriding UITabbarController for a custom one and implement the following method:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;

Next loop trough all the 'viewcontrollers' of the tabbar (in this case the navigation controllers) and call on all the navigation controllers popToRootViewController.

This might work.



来源:https://stackoverflow.com/questions/18720228/calling-poptoviewcontroller-function-from-a-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!