iOS菜鸟联盟UI基础

iOS 获取当前window显示的控制器并返回到首页。

2018-03-01  本文已影响1305人  走向菜鸟的菜鸟
温馨提示:具体情况还要具体分析,本篇文章处理跳转逻辑不一定符合您的项目,请分析后进行修改使用。

思路:
将这个需求划分成两部分进行处理:
1️⃣获取当前window显示的控制器。
2️⃣从当前控制器返回到首页。

第一步:获取当前window显示的控制器

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC {
    
    UIViewController *result = nil;
    
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    do {
        if ([rootVC isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navi = (UINavigationController *)rootVC;
            UIViewController *vc = [navi.viewControllers lastObject];
            result = vc;
            rootVC = vc.presentedViewController;
            continue;
        } else if([rootVC isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tab = (UITabBarController *)rootVC;
            result = tab;
            rootVC = [tab.viewControllers objectAtIndex:tab.selectedIndex];
            continue;
        } else if([rootVC isKindOfClass:[UIViewController class]]) {
            result = rootVC;
            rootVC = nil;
        }
    } while (rootVC != nil);
    
    return result;
}

第二步:判断当前window显示的控制器的跳转方式(Push or Modal)
①:判断currentVC.presentingViewController是否存在?

如果是单个控制器Modal(A跳转B,B返回A),使用
[self dismissViewControllerAnimated:YES completion:nil];  
如果是多个控制器Modal(A跳转B,B跳转C,C返回A),使用
UIViewController *rootVC = self.presentingViewController;
while (rootVC.presentingViewController) {
     rootVC = rootVC.presentingViewController;
}
[rootVC dismissViewControllerAnimated:YES completion:nil];
使用 [currentVC.navigationController popToRootViewControllerAnimated:YES]; 

②:根据①的判断进行跳转的逻辑处理
注意:如果是基于tabBarController的控制器currentVC.presentingViewController获取的控制器类型UITabBarController,相关解释请查看这篇文章

+ (void)chooseToJumpHome {
    UIViewController *currentVC = [self getCurrentVC];
    if (currentVC.presentingViewController) {
       [currentVC dismissViewControllerAnimated:NO completion:^{
            // 此处为注意点,处理当前界面是先push再modal出来而显示的控制器(处理方式:先dismiss,再pop)如果获取的currentVC.presentingViewController是UITabBarController,则无法进行pop操作了。
            if ([currentVC.presentingViewController isKindOfClass:[UINavigationController class]]) {
                UINavigationController *navi = (UINavigationController *)currentVC.presentingViewController;
                [navi popToRootViewControllerAnimated:NO];
            }
        }];
    } else {
        [currentVC.navigationController popToRootViewControllerAnimated:NO];
    }
    
    UITabBarController *rootTab = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    rootTab.selectedIndex = 0;
}
上一篇 下一篇

猜你喜欢

热点阅读