iOS开发中,在没有用到navigationController情况下,页面跳转多用present,但它并没有一个类似popToRootViewControllerAnimated的方法可以直接回到根控制器,下面给出三个方法:



方法一:循环获取到最底层控制器,然后dismiss掉,直接返回到跟控制器


- (void)logoutBtnOnClick    
{    
    UIViewController *vc = self.presentingViewController;    
        
    if (!vc.presentingViewController)   return;    
        
    while (vc.presentingViewController)  {    
        vc = vc.presentingViewController;    
    }    
        
    [vc dismissViewControllerAnimated:YES completion:nil];    
}  

方法二:在方法一中稍作修改,通过判断直接dismiss到目标控制器


- (void)logoutBtnOnClick    
{    
    TargetVC *target = [[TargeVC alloc] init];    
        
    UIViewController *vc = self.presentingViewController;    
        
    if (!vc.presentingViewController) return;    
        
    while (![vc isKindOfClass:[target class]])  {    
        vc = vc.presentingViewController;    
    }    
        
    [vc dismissViewControllerAnimated:YES completion:nil];    
}  

方法三:逐级获取,然后dismiss掉,可以回到想要的控制器(如:A→B→C→D逐级present后由D想回到B)

// 一个presentingViewController返回一级
if ([self respondsToSelector:@selector(presentingViewController)]) {    
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];    
}