iOS-獲取當前View所在的控制器

在做輪播圖的時候,有點輪播圖展示的是廣告,有的是活動,等等還有其他的

當前點擊某個輪播的時候要跳轉到不同的控制器,點擊事件是在控制器寫的,爲了避免控制器代碼過多,顯示的臃腫

我創建了一個UIWindow的分類,暫且叫Model (GetCurrentVC)

谷歌還有很多方法,我這個方法親測有效,其他方法後續再測試

一:

@interface UIWindow (GetCurrentVC)

- (UIViewController *)getCurrentVC;

@end

二:


#import "UIWindow+GetCurrentVC.h"


@implementation UIWindow (GetCurrentVC)


-  (UIViewController *)getCurrentVC {

    UIViewController *result = nil;

    

    UIWindow * window = [[UIApplication sharedApplication] keyWindow];

    if (window.windowLevel != UIWindowLevelNormal)

    {

        NSArray *windows = [[UIApplication sharedApplication] windows];

        for(UIWindow * tmpWin in windows)

        {

            if (tmpWin.windowLevel == UIWindowLevelNormal)

            {

                window = tmpWin;

                break;

            }

        }

    }

    

    UIView *frontView = [[window subviews] objectAtIndex:0];

    id nextResponder = [frontView nextResponder];

    

    if ([nextResponder isKindOfClass:[UIViewController class]])

        result = nextResponder;

    else

        result = window.rootViewController;

    

    return result;

}



@end






發佈了45 篇原創文章 · 獲贊 9 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章