How do you check current view controller class in Swift?

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

    Swift 3 | Check if a view controller is the root from within itself.

    You can access window from within a view controller, you just need to use self.view.window.

    Context: I need to update the position of a view and trigger an animation when the device is rotated. I only want to do this if the view controller is active.

    class MyViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            NotificationCenter.default.addObserver(
                self, 
                selector: #selector(deviceDidRotate), 
                name: .UIApplicationDidChangeStatusBarOrientation, 
                object: nil
            )
        }
    
        func deviceDidRotate() {
            guard let window = self.view.window else { return }
    
            // check if self is root view controller
            if window.rootViewController == self {
                print("vc is self")
            }
    
            // check if root view controller is instance of MyViewController
            if window.rootViewController is MyViewController {
                print("vc is MyViewController")
            }
        }
    }
    

    If you rotate your device while MyViewController is active, you will see the above lines print to the console. If MyViewController is not active, you will not see them.

    If you're curious why I'm using UIDeviceOrientationDidChange instead of .UIDeviceOrientationDidChange, look at this answer.

提交回复
热议问题