Swift4 Get the topmost controller of the current page

Conform to  UITabBarController ---> UINavigationController layout


//MARK: Get the topmost controller of the current page

func getCurrentVCBS() -> UIViewController {
    let keywindow = UIApplication.shared.keyWindow
    let firstView: UIView = (keywindow?.subviews.first)!
    let secondView: UIView = firstView.subviews.first!
    var vc = viewForController(view: secondView)!
    vc = ((vc as! UITabBarController).selectedViewController! as! UINavigationController).visibleViewController!
  
    return you
}

private func viewForController(view:UIView)->UIViewController?{
    var next:UIView? = view
    repeat{
        if let nextResponder = next?.next, nextResponder is UIViewController {
            return (nextResponder as! UIViewController)
        }
        next = next?.superview
    }while next != nil
    return nil
}

//MARK: Check the correctness of the result

//classType: current page class type
func vcResult(classType: UIViewController.Type) -> Bool {
    return getCurrentVCBS().isKind(of: classType)
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899427&siteId=291194637