在AppDelegate怎么获取到当前的controller?

在接受到remote notification后,我想跳转到D controller。 但是D controller的目录结构很深, A->B->C->D 一层层push过去的, 我这时候该怎么跳呢? 是不是 应该直接从Apush到D? 回退的时候 D 回退到A

还是应该获取到当前controller 然后push到D controller呢?(在AppDelegate怎么获取到当前的controller)
ps navigation 有一个visibleViewController 方法,可以获取到当前的controller,这种思路对不?

阅读 13.4k
3 个回答

如果是在UINavigationController得子层级,直接UINavigationController push D controller是最好的实现,以用户的角度并不想A,B,C,D一层一层的push下去,然后再D,C,B,A一层一层的返回。

这种push操作并不需要获取当前的viewController.如果想获取UINavigationController子层级的当前显示的viewController ,可以通过UINavitionController的topViewController获取

如果是用UINavigationController来组织页面结构的话可以使用:

((UINavigationController*)appDelegate.window.rootViewController).visibleViewController;

如果是用UITabBarController来组织页面结构的话:

((UITabBarController*)appDelegate.window.rootViewController).selectedViewController;
-(UIViewController *)currentViewController
{
    
    UIViewController * currVC = nil;
    UIViewController * Rootvc = self.window.rootViewController ;
    do {
        if ([Rootvc isKindOfClass:[UINavigationController class]]) {
            UINavigationController * nav = (UINavigationController *)Rootvc;
            UIViewController * v = [nav.viewControllers lastObject];
            currVC = v;
            Rootvc = v.presentedViewController;
            continue;
        }else if([Rootvc isKindOfClass:[UITabBarController class]]){
            UITabBarController * tabVC = (UITabBarController *)Rootvc;
            currVC = tabVC;
            Rootvc = [tabVC.viewControllers objectAtIndex:tabVC.selectedIndex];
            continue;
        }else if ([Rootvc isKindOfClass:[XXXCustom class]]){
            XXXCustom * tabVC = (XXXCustom *)Rootvc;
            currVC = tabVC;
            Rootvc = tabVC.selectedViewController;
            continue;
        } 
    } while (Rootvc!=nil);
    

    return currVC;
}```
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题