经常会用到的两种方式获取当前控制器,一般我们都会把这个方法写在AppDelegate文件里。
1、用tabBarController的时候
//返回当前的VC
- (UIViewController *)getNowViewController
{
UIViewController *reController = nil;
//当前用的tabBarController
if (_tabBarController!=nil)
{
UINavigationController *nav = (UINavigationController *)[[_tabBarController viewControllers] objectAtIndex:_tabBarController.selectedIndex];
UIViewController *topController = [nav topViewController];
id tempViewController = topController;
while ([(UIViewController *)tempViewController presentedViewController]!=nil)
{
tempViewController = [(UIViewController *)tempViewController presentedViewController];
}
if (tempViewController!=nil)
{
if ([tempViewController isKindOfClass:[UINavigationController class]])
{
reController = [(UINavigationController *)tempViewController topViewController];
}
else
{
reController = tempViewController;
}
}
else
{
reController = topController;
}
}
//NSLog(@"getNowViewController is %@....",[reController class]);
return reController;
}
2、平常的用法
#pragma mark - 获取当前控制器
-(UIViewController *)getCurrentController{
UIViewController *reController = nil;
UIWindow *window = [[UIApplication sharedApplication]keyWindow];
if (window.windowLevel!= UIWindowLevelNormal) {
NSArray *array = [[UIApplication sharedApplication]windows];
for (UIWindow *win in array) {
if (win.windowLevel == UIWindowLevelNormal) {
window = win;
break;
}
}
}
UIView *cuView = [[window subviews]objectAtIndex:0];
id responder = [cuView nextResponder];
if ([responder isKindOfClass:[UIViewController class]]) {
reController = responder;
}
else{
reController = window.rootViewController;
}
return reController;
}
3、还有一种情况是用到了UINavigationController但没有用tabBarController。我们在AppDelegate.h文件声明一个UINavigationController的属性,然后在AppDelegate.m文件里实现方法。在使用的时候记得是用self.nav推出控制器!
#pragma mark - 返回当前的控制器
- (UIViewController *)getNowViewController
{
UIViewController *reController = nil;
//当前用的navController
UINavigationController *nav = self.nav;
UIViewController *topController = [nav topViewController];
id tempViewController = topController;
while ([(UIViewController *)tempViewController presentedViewController]!=nil)
{
tempViewController = [(UIViewController *)tempViewController presentedViewController];
}
if (tempViewController!=nil)
{
if ([tempViewController isKindOfClass:[UINavigationController class]])
{
reController = [(UINavigationController *)tempViewController topViewController];
}
else
{
reController = tempViewController;
}
}
else
{
reController = topController;
}
return reController;
}
END.