swift 获取app当前视图控制器,回退到根控制器

获取当前的控制器,代码如下

func currentViewController() -> UIViewController{

    var currentVC: UIViewController? = self.window?.rootViewController

    while (current?.presentedViewController != nil) {

        currentVC = currentVC.presentedViewController

    }

    if (currentVC?.isKind(of: UITaberViewController.self))! {

        currentVC = (currentVC as! UITaberViewController).selectedViewController

    }

    if (currentVC?.isKind(of: UINavigationController.self))! {

        currentVC = (currentVC as! UINavigationController).visibleViewController

    }

    return currentVC!

}

回退到根控制器

func backToRoot() {

    let currentVC = self.currentVIewController()

    var rootVC = (current as UIViewController).presentingViewController

if rootVC != nil {

    while( rootVC.presentingVIewCOntroller != nil) {

        rootVC = rootVC.presentingViewController

    }

    if ((rootVC?.responds(to: #selector(UIViewController.dismiss(animated:completion:))) == true){

        (root as! UINavigationController).popToRootViewController(animated:false)

    }

 }else{

currentVC.navigationController?.popToRootViewController(animated:false)

 }

}

你可能感兴趣的:(swift 获取app当前视图控制器,回退到根控制器)