月圆之夜,紫禁之巅,一剑西来,天外飞仙。

0%

iOS 中获取当前视图所在的ViewController

1
闲言少叙,直接上代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
+(UIViewController *)getCurrentVC
{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];

return currentVC;
}

+(UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
UIViewController *currentVC;

if ([rootVC presentedViewController]) {


rootVC = [rootVC presentedViewController];
}

if ([rootVC isKindOfClass:[UITabBarController class]]) {


currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];

} else if ([rootVC isKindOfClass:[UINavigationController class]]){


currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];

} else {


currentVC = rootVC;
}

return currentVC;
}