1. 程式人生 > >獲取當前控制器,封裝方法可直接呼叫

獲取當前控制器,封裝方法可直接呼叫

                                                    

實際開發中,經常會遇到彈窗,在彈窗中有點選事件,然後跳轉到指定頁面。比如當前頁面,點選上架,會顯示彈窗顯示當前上架總數,並且右邊按鈕可以跳轉到店鋪頁面。那麼問題來了。通常情況下這種彈窗都是一個view加在當前keywindow上。先來看一下彈窗的原始碼,在訪問請求成功的情況下,將我們分裝好的putawayview放到key window上

if ([dic[kFlag] isEqualToString:@"1"]) {
                
                [SSGOTools showInfoPopHint:@"上架成功"];
                
                PutAwayView * view = [[PutAwayView alloc]initWithFrame:CGRectMake(0,kScreenHeight -91 -X_HOME_INDICATOR_HEIGHT, kScreenWidth , 91 )];
                [view updateViewWithBean:dic[kMsg]];
                __weak PutAwayView * weakView = view;
                weakView.shopblock = ^(NSInteger tag) {
                    if (tag == 102) {
                     
                        ShopListVC *vc = [ShopListVC new];
                        [[SSGOTools getCurrentViewController].navigationController pushViewController:vc animated:YES];
                    }
                };
                UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                [window addSubview:view];
                
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [view removeFromSuperview];
                });
                
            }

通過view的block回撥,我們推出一個新的頁面。到店鋪頁面。那麼如何獲得當前的window背後顯示的控制器呢?這裡需要一個方法,已經封裝成類方法,拿來直接用即可,程式碼如下:

+(UIViewController *)getCurrentViewController
{
    return [SSGOTools topViewControllerWithRootViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
}

+ (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
    if ([rootViewController isKindOfClass:[RDVTabBarController class]]) {
        RDVTabBarController *tabBarController = (RDVTabBarController *)rootViewController;
        return [SSGOTools topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [SSGOTools topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [SSGOTools topViewControllerWithRootViewController:presentedViewController];
    } else if ( [rootViewController isKindOfClass:[UIPageViewController class]]){
        UIPageViewController * pageViewController = (UIPageViewController*)rootViewController;
        return  pageViewController.viewControllers[0];
        
    }else {
        return rootViewController;
    }
}