獲取當前控制器(viewController)

weixin_34321977發表於2016-12-07

 剛才在網上看到一個這樣的文章,感覺很不科學!所以就自己搞一下這個東西,希望大家指正!

廢話不多說,直接上程式碼.


-(UIViewController*)getCurrentViewController

{

UIViewController* viewController =nil;

UIWindow* window = [UIApplicationsharedApplication].delegate.window;

if(window.windowLevel!=UIWindowLevelNormal)

{

NSArray* array = [UIApplicationsharedApplication].windows;

for(UIWindow* windowCurrentinarray)

{

if(windowCurrent.windowLevel==UIWindowLevelNormal)

{

window = windowCurrent;

break;

}

}

}

UIView* view = [[windowsubviews]objectAtIndex:0];

idnextResponder = [viewnextResponder];

if([nextResponderisKindOfClass:[UITabBarControllerclass]])

{

UITabBarController* tabbarViewcontroller = (UITabBarController*)nextResponder;

UINavigationController* navigationController = tabbarViewcontroller.selectedViewController;

viewController = navigationController.topViewController;

}

elseif([nextResponderisKindOfClass:[UIViewControllerclass]])

{

viewController = nextResponder;

}

else

{

viewController = window.rootViewController;

}

returnviewController;

}

歡迎大家批評指正!

相關文章