IOS獲取當前所在的ViewController


這個主要用於給別人提供的API中,有關跳轉的地方。在IOS中,跳轉必須提供目前所在的ViewController。代碼如下:

// 獲取當前顯示的 UIViewController
+ (UIViewController *)dc_findCurrentShowingViewController {
    //獲得當前活動窗口的根視圖
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentShowingVC = [self findCurrentShowingViewControllerFrom:vc];
    return currentShowingVC;
}
+ (UIViewController *)findCurrentShowingViewControllerFrom:(UIViewController *)vc
{
    // 遞歸方法 Recursive method
    UIViewController *currentShowingVC;
    if ([vc presentedViewController]) {
        // 當前視圖是被presented出來的
        UIViewController *nextRootVC = [vc presentedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];

    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // 根視圖為UITabBarController
        UIViewController *nextRootVC = [(UITabBarController *)vc selectedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];

    } else if ([vc isKindOfClass:[UINavigationController class]]){
        // 根視圖為UINavigationController
        UIViewController *nextRootVC = [(UINavigationController *)vc visibleViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];

    } else {
        // 根視圖為非導航類
        currentShowingVC = vc;
    }

    return currentShowingVC;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM