图片来自网络
//获取当前屏幕 显示的viewcontroller
- (UIViewController *)getCurrentVC
{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *currentVC = [self getCurrentVCFromRootVC:rootViewController];
return currentVC;
}
- (UIViewController *) getCurrentVCFromRootVC:(UIViewController *)rootVC
{
UIViewController *currentVC;
if ([rootVC presentedViewController]) {
// 视图是被presented出来的
rootVC = [rootVC presentedViewController];
}
if ([rootVC isKindOfClass:[UITabBarController class]]) {
// 根视图是:UITabBarController
currentVC = [self getCurrentVCFromRootVC:[(UITabBarController *)rootVC selectedViewController]];
} else if ([rootVC isKindOfClass:[UINavigationController class]]){
// 根视图是:UINavigationController
currentVC = [self getCurrentVCFromRootVC:[(UINavigationController *)rootVC visibleViewController]];
} else {
// 根视图是:非导航类、非标签类
currentVC = rootVC;
}
return currentVC;
}
复制代码
方法的使用:
UIViewController *topVC = [self getCurrentVC]; 复制代码
由于是AppDelegate单例类的原因,在其他任何地方都可以添加、使用 上述方法!
当然我们也可以单独为“AppDelegate” 添加该方法 或 添加类别,之后直接调用 就可以了!可提高代码的复用性,简化代码量!
(2017.11.03)
goyohol’s essay
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END