How do you check current view controller class in Swift?

前端 未结 15 755
梦谈多话
梦谈多话 2020-12-13 01:50

As far as I know, this would work in Objective-C:

self.window.rootViewController.class == myViewController

How can I check if the current v

相关标签:
15条回答
  • 2020-12-13 01:52

    I had to find the current viewController in AppDelegate. I used this

    //at top of class
    var window:UIWindow?
    
    // inside my method/function
    if let viewControllers = window?.rootViewController?.childViewControllers {
        for viewController in viewControllers {
            if viewController.isKindOfClass(MyViewControllerClass) {
                println("Found it!!!")
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-13 01:53

    Check that way that worked better for me What is .self

    if ((self.window.rootViewController?.isKind(of: WebViewController.self))!)
    {
      //code
    }
    
    0 讨论(0)
  • 2020-12-13 02:01
    let viewControllers = navController?.viewControllers
            for aViewController in viewControllers! {
    
                if aViewController .isKind(of: (MyClass?.classForCoder)!) {
                    _ = navController?.popToViewController(aViewController, animated: true)
                }
            }
    
    0 讨论(0)
  • 2020-12-13 02:03

    To go off of Thapa's answer, you need to cast to the viewcontroller class before using...

       if let wd = self.view.window {
            var vc = wd.rootViewController!
            if(vc is UINavigationController){
                vc = (vc as! UINavigationController).visibleViewController
            }
            if(vc is customViewController){
                var viewController : customViewController = vc as! customViewController
    
    0 讨论(0)
  • 2020-12-13 02:03

    My suggestion is a variation on Kiran's answer above. I used this in a project.

    Swift 5

    // convenience property API on my class object to provide access to the my WindowController (MyController).
    var myXWindowController: MyController? {
    
        var myWC: MyController?                
        for viewController in self.windowControllers {
            if ((viewController as? MyController) != nil) {
                myWC = viewController as? MyController
                break
            }
        }
    
        return myWC
    }
    
    // example of use
    guard let myController = myXWindowController else {
        reportAssertionFailure("Failed to get MyXController from WindowController.")
        return
    }  
    
    0 讨论(0)
  • 2020-12-13 02:03
     var top = window?.rootViewController
                while ((top?.presentedViewController) != nil) {
                    top = top?.presentedViewController
                }
                
                if !(type(of: top!) === CallingVC.self) {
                    top?.performSegue(withIdentifier: "CallingVC", sender: call)
                }
    
    0 讨论(0)
提交回复
热议问题