How do you check current view controller class in Swift?

前端 未结 15 754
梦谈多话
梦谈多话 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 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
    }  
    

提交回复
热议问题