I want to check if the view controller i am in is root view controller or is pushed on some navigation controller.
[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
}
self
into the placeholder in the if check and it will work, because my code will compare the 2 objects and return true if they are the same. The position in the navigation stack is irrelevant to my answer –
Nautilus Whenever you push any view controller via navigation controller, it manages these view controllers on a stack which is maintained in Last In First Out manner. So if your current view controller is root controller than there can be only one object in the stack. You can check that stack via this code
if([self.navigationController.viewControllers count] == 1) {
//Current view controller is root controller
}
in your current View controller's viewDidLoad just check self.navigationController.viewControllers.count == 1
mean you are currently in rootview of your navigationstack. make sure you haven't present viewcontroller.
if(self.navigationController.viewControllers.count == 1)
{
//do what you want
}
With respect to @Simon answer, I'm adding my answer, to check when you're using some drawer menu, this may help you to find exact root view controller check.
- (BOOL) checkImRoot:(id)controller {
if(self.window.rootViewController) {
if(self.window.rootViewController == (UIViewController *)controller) {
return YES;
}
}
return NO;
}
In example, I'm adding this method in app delegate file, and calling it like this to check,
if([[AppDelegate shareDelegate] checkImRoot:self]) {
//Yeah, I'm a root vc
}else{
//Noo, I'm a child vc
}
self.window.rootViewController
?! Is that a mistake? –
Slay window
property. –
Triptolemus nil
. Why have the extra line?! –
Slay rootViewController
will be nil
? Then our comparison might crash our code. –
Triptolemus rootViewController
is an optional... –
Slay © 2022 - 2024 — McMap. All rights reserved.
self.navigationController.viewControllers
it will give you array of your pushed navigation viewcontrollers – Transcendentself.navigationController.topViewController == self
to check if it is therootViewController
– Custombuilt