获取顶层视图控制器UIViewController

Objective-c版本:

+ (UIViewController *)getCurrentVC
{
  UIViewController *RootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
  UIViewController *currentVC = RootVC;
  while (currentVC.presentedViewController) {
    currentVC = currentVC.presentedViewController;
  }
  return currentVC;
}

Swift版本:

func getCurrentVC()-> UIViewController? {
    var RootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while RootVC?.presentedViewController != nil {
      RootVC = RootVC?.presentedViewController
    }
    return RootVC
}

你可能感兴趣的:(iOS)