美文网首页
swift查找当前ViewVontroller

swift查找当前ViewVontroller

作者: 微凉初夏 | 来源:发表于2018-07-20 15:33 被阅读0次
    final class FindHelper {
    
    static let share = FindHelper()
    
    var currentViewCotroller: UIViewController? {
        
        var result: UIViewController? = nil
        var window: UIWindow
        
        guard let _window = UIApplication.shared.keyWindow else {
            return result
        }
        window = _window
        
        if window.windowLevel != UIWindow.Level.normal {
            guard let _tmpWin =  UIApplication.shared.windows
                .filter({ $0.windowLevel == UIWindow.Level.normal })
                .first else {
                    return result
            }
            window = _tmpWin
        }
        
        var nextResponder: UIResponder? = nil
        let appRootVC = window.rootViewController
        
        // 如果是present上来的appRootVC.presentedViewController 不为nil
        if let presentedVC = appRootVC?.presentedViewController {
            nextResponder = presentedVC
        } else {
            let frontView = window.subviews[0]
            nextResponder = frontView.next
        }
        
        if let tabbar = nextResponder as? UITabBarController {
            if let nav = tabbar.viewControllers?[tabbar.selectedIndex] as? UINavigationController {
                result = nav.children.last
            }
        } else if let nav = nextResponder as? UINavigationController {
            result = nav.children.last
        } else {
            result = nextResponder as? UIViewController
        }
        
        return result
    }
    }

    相关文章

      网友评论

          本文标题:swift查找当前ViewVontroller

          本文链接:https://www.haomeiwen.com/subject/eehqmftx.html