UIViewController 相关的方法

iOS 获取当前正在显示的ViewController
原文

  • 1.我们在非视图类中想要随时展示一个view时,需要将被展示的view加到当前view的子视图,或用当前view presentViewController,或pushViewContrller,这些操作都需要获当前正在显示的ViewController。

    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
    //获取当前屏幕显示的viewcontroller
    - (UIViewController *)getCurrentVC
    {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for(UIWindow * tmpWin in windows)
    {
    if (tmpWin.windowLevel == UIWindowLevelNormal)
    {
    window = tmpWin;
    break;
    }
    }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
    result = nextResponder;
    else
    result = window.rootViewController;
    return result;
    }
  • 2.获取当前屏幕中present出来的viewcontroller

1
2
3
4
5
6
7
8
9
10
- (UIViewController *)getPresentedViewController
{
UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *topVC = appRootVC;
if (topVC.presentedViewController) {
topVC = topVC.presentedViewController;
}
return topVC;
}