Swift 返回到根视图或指定页面

一、dissmiss返回到根视图
    func dissmissRootViewController()  {
        //1.直接跳回到根视图
        //1.1 直接通过 window.rootViewController 获取根VC,再dissmiss,达不到理想效果
        //       self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
        
        
        //1.2循环调用 presentingViewController 获取根VC,再dissmiss
        //获取根VC
        var rootVC = self.presentingViewController
        while let parent = rootVC?.presentingViewController {
            rootVC = parent
        }
        //释放所有下级视图
        rootVC?.dismiss(animated: true, completion: nil)
        
        //2.连续dissmiss两个视图
        //        self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
    }
二、pop返回到指定页面
    func goMeViewController()  {
        self.navigationController?.popToRootViewController(animated: true)
        guard let delegate = UIApplication.shared.delegate as? AppDelegate,let tabBarController = delegate.window?.rootViewController as? UITabBarController, let viewControllers = tabBarController.viewControllers  else {
            return
        }
        
        for item in viewControllers {
            guard let navController = item as? UINavigationController, let rootViewController = navController.viewControllers.first else { continue }
            if rootViewController is MeMainViewController {
                tabBarController.selectedViewController = navController
                break
            }
        }
    }

你可能感兴趣的:(Swift 返回到根视图或指定页面)