How do you check current view controller class in Swift?

前端 未结 15 756
梦谈多话
梦谈多话 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:18

    For types you can use is and if it is your own viewcontroller class then you need to use isKindOfClass like:

    let vcOnTop = self.embeddedNav.viewControllers[self.embeddedNav.viewControllers.count-1]
                if vcOnTop.isKindOfClass(VcShowDirections){
                    return
                }
    
    0 讨论(0)
  • 2020-12-13 02:19

    Try this

    if self is MyViewController {        
    
    }
    
    0 讨论(0)
  • 2020-12-13 02:19

    Swift 3

    Not sure about you guys, but I'm having a hard time with this one. I did something like this:

    if let window = UIApplication.shared.delegate?.window {
        if var viewController = window?.rootViewController {
            // handle navigation controllers
            if(viewController is UINavigationController){
                viewController = (viewController as! UINavigationController).visibleViewController!
            }
            print(viewController)
        }
    }
    

    I kept getting the initial view controller of my app. For some reason it wanted to stay the root view controller no matter what. So I just made a global string type variable currentViewController and set its value myself in each viewDidLoad(). All I needed was to tell which screen I was on & this works perfectly for me.

    0 讨论(0)
提交回复
热议问题