获取当前视图控制器
2017-04-10 本文已影响0人
奇流府
.h 中暴露接口
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
UIViewController * currentVC();
.m 中实现
#import "HelpMethodManager.h"
UIViewController * findBestVC(UIViewController *vc) {
if (vc.presentedViewController) {
return findBestVC(vc.presentedViewController);
} else if ([vc isKindOfClass:[UISplitViewController class]]) {
UISplitViewController *sp = (UISplitViewController *)vc;
return sp.viewControllers.count > 0 ? findBestVC(sp.viewControllers.lastObject) : vc;
} else if ([vc isKindOfClass:[UINavigationController class]]) {
UINavigationController *na = (UINavigationController *)vc;
return na.viewControllers.count > 0 ? findBestVC(na.topViewController) : vc;
} else if ([vc isKindOfClass:[UITabBarController class]]) {
UITabBarController *ta = (UITabBarController *)vc;
return ta.viewControllers.count > 0 ? findBestVC(ta.selectedViewController) : vc;
}
return vc;
}
UIViewController * currentVC() {
UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
return findBestVC(rootVC);
}
如果页面跳转,currentVC() 的值也将改变,他永远获取当前页面的控制器。