As far as I know, this would work in Objective-C:
self.window.rootViewController.class == myViewController
How can I check if the current v
if let index = self.navigationController?.viewControllers.index(where: { $0 is MyViewController }) {
let vc = self.navigationController?.viewControllers[vcIndex] as! MyViewController
self.navigationController?.popToViewController(vc, animated: true)
} else {
self.navigationController?.popToRootViewController(animated: true)
}
To check the class in Swift, use "is" (as explained under "checking Type" in the chapter called Type Casting in the Swift Programming Guide)
if self.window.rootViewController is MyViewController {
//do something if it's an instance of that class
}
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.
Updated for swift3 compiler throwing a fit around ! and ?
if let wd = UIApplication.shared.delegate?.window {
var vc = wd!.rootViewController
if(vc is UINavigationController){
vc = (vc as! UINavigationController).visibleViewController
}
if(vc is LogInViewController){
//your code
}
}
Swift 4, Swift 5
let viewController = UIApplication.shared.keyWindow?.rootViewController
if viewController is MyViewController {
}
You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
// some process
if viewController.isKindOfClass(MenuViewController) {
println("yes it is")
}
}
}