获取当前界面所对应视图控制器方法(封装方式:公共方法、Category由个人喜好自行斟酌)
- (UIViewController *)getCurrentViewController{
UIViewController *currentViewController = [self getRootViewController];//获取根视图UIWindow.rootViewController
while (1) {
//使控制器呈现的方法有两种:UINavigationController的push 、 UIViewController的present
if(currentViewController.presentedViewController){//判断当前控制器是否t以present方式呈现
currentViewController = currentViewController.presentedViewController;
}else if([currentViewController isKindOfClass:[UITabBarController class]]){//判断是否为UITabBarController对象
UITabBarController *tabBarController =(UITabBarController *)currentViewController;
currentViewController = tabBarController.selectedViewController;
}else if([currentViewController isKindOfClass:[UINavigationController class]]){//判断是否为UINavigationControler对象
UINavigationController* navigationController = (UINavigationController* )currentViewController;
currentViewController = navigationController.visibleViewController;
}else{
NSUInteger childViewControllerCount = currentViewController.childViewControllers.count;
if(childViewControllerCount > 0){//判断当前控制器是否有子控制器
currentViewController = currentViewController.childViewControllers.lastObject;//取其子控制器栈顶对象
}
break;
}
}
return currentViewController;
}
获取根视图控制器方法
- (UIViewController *)getRootViewController{
UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
NSAssert(window, @"The window is empty");
return window.rootViewController;
}