經常會用到的兩種方式獲取當前控制器歼捏,一般我們都會把這個方法寫在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.