本文主要是介绍[Swift]获取最顶层视图控制器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/// 验证
func verificationAction(code:Int) {guard let topVC = ScreenUIManager.topViewController() else {return}let vc = AppSafeVerificationVC()vc.reCode = codevc.modalPresentationStyle = .overCurrentContextvc.modalTransitionStyle = .coverVerticalvc.view.backgroundColor = .cleartopVC.present(vc, animated: true) {}
}
import UIKitclass ScreenUIManager: NSObject {/// 获取顶部控制器 无要求static func topViewController() -> UIViewController? {var window = UIApplication.shared.keyWindow// 是否为当前显示的windowif ((window?.windowLevel.rawValue) != 0) {let windows = UIApplication.shared.windowsfor windowTemp in windows{if windowTemp.windowLevel.rawValue == 0{window = windowTempbreak}}}let vc = window?.rootViewControllerreturn getTopVC(withCurrentVC: vc)}static func getTopVC(withCurrentVC VC:UIViewController?) -> UIViewController? {if VC == nil {return nil}if let presentVC = VC?.presentedViewController {//modal出来的 控制器return getTopVC(withCurrentVC: presentVC)}else if let tabVC = VC as? UITabBarController {// tabBar 的跟控制器if let selectVC = tabVC.selectedViewController {return getTopVC(withCurrentVC: selectVC)}return nil} else if let naiVC = VC as? UINavigationController {// 控制器是 navreturn getTopVC(withCurrentVC:naiVC.visibleViewController)} else {// 返回顶控制器return VC}}}
popToViewController
func goback() {guard let children = self?.navigationController?.children, children.count > 2 else {self?.popToRootVC()return}let presentVC = children[children.count - 3]self?.navigationController?.popToViewController(presentVC, animated: true)
}
func goback() {let childs = self.navigationController!.childrenfor vc in childs {if vc.isKind(of: TransferVC.self) {self.navigationController?.popToViewController(vc, animated: false)return}}
}
这篇关于[Swift]获取最顶层视图控制器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!