How do I get the RootViewController from a pushed controller?

前端 未结 9 1450
小鲜肉
小鲜肉 2020-12-04 07:50

So, I push a view controller from RootViewController like:

[self.navigationController pushViewController:anotherViewController animated:YES] ;

BUT, FRO

9条回答
  •  离开以前
    2020-12-04 08:09

    As an addition to @dulgan's answer, it is always a good approach to use firstObject over objectAtIndex:0, because while first one returns nil if there is no object in the array, latter one throws exception.

    UIViewController *rootViewController = self.navigationController.rootViewController;
    

    Alternatively, it'd be a big plus for you to create a category named UINavigationController+Additions and define your method in that.

    @interface UINavigationController (Additions)
    
    - (UIViewController *)rootViewController;
    
    @end
    
    @implementation UINavigationController (Additions)
    
    - (UIViewController *)rootViewController
    {
        return self.viewControllers.firstObject;
    }
    
    @end
    

提交回复
热议问题