I want to check if the view controller i am in is root view controller or is pushed on some navigation controller.
The root view controller is simply the view controller that sits at the bottom of the navigation stack. You can access the navigation controller's array of view controllers through its viewControllers property. To access the root view controller, we ask for the first item of the array of view controllers.
The view's window property is non-nil if a view is currently visible, so check the main view in the view controller: Invoking the view method causes the view to load (if it is not loaded) which is unnecessary and may be undesirable. It would be better to check first to see if it is already loaded.
The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller's view as the content view of the window.
[self.navigationController viewControllers];
will return an array of all the viewControllers on the stack. Simply compare the first element in this array to see is the controller the root or not.
e.g.
UIViewController *vc = [[self.navigationController viewControllers] firstObject];
if([vc isEqual: <viewController to check> ])
{
// code here
}
EDIT: Add Swift
let vc = self.navigationController?.viewControllers.first
if vc == self.navigationController?.visibleViewController {
//Code Here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With