How do I get the RootViewController from a pushed controller?(如何从推送的控制器中获取 RootViewController?)
问题描述
所以,我从 RootViewController 推送一个视图控制器,例如:
<上一页>[self.navigationController pushViewController:anotherViewController Animation:YES] ;但是,从 anotherViewController 现在,我想再次访问 RootViewController.
我在努力
<上一页>//(现在在另一个视图控制器中)///RootViewController *root = (RootViewController*)self.parentViewController ;//不.//呃RootViewController *root = (RootViewController*)[self.navigationController.viewControllers objectAtIndex:0] ;//是的!!有用我不确定为什么这样做有效,我不确定这是否是最好的方法.有人可以评论从您推送到该 RootViewController 的 navigationController 的控制器中获取 RootViewController 的更好方法以及我所做的方式是否可靠?
使用viewControllers 属性.示例代码:
//在另一个 ViewController 中NSArray *viewControllers = self.navigationController.viewControllers;UIViewController *rootViewController = [viewControllers objectAtIndex:viewControllers.count - 2];这是获取后退"视图控制器的标准方法.objectAtIndex:0 起作用的原因是因为您尝试访问的视图控制器也是根视图,如果您在导航中更深入,则后视图与根视图不同.
So, I push a view controller from RootViewController like:
[self.navigationController pushViewController:anotherViewController animated:YES] ;
BUT, FROM anotherViewController now, I want to access the RootViewController again.
I'm trying
// (inside anotherViewController now) ///RootViewController *root = (RootViewController*)self.parentViewController ; // No. // err RootViewController *root = (RootViewController*)[self.navigationController.viewControllers objectAtIndex:0] ; // YES!! it works
I'm not sure WHY this works and I'm not sure if its the best way to do it. Can somebody comment on a better way to get the RootViewController from a controller you've pushed into that RootViewController's navigationController and whether or not the way I've done it is reliable or not?
Use the viewControllers property of the UINavigationController. Example code:
// Inside another ViewController
NSArray *viewControllers = self.navigationController.viewControllers;
UIViewController *rootViewController = [viewControllers objectAtIndex:viewControllers.count - 2];
This is the standard way of getting the "back" view controller. The reason objectAtIndex:0 works is because the view controller you're trying to access is also the root one, if you were deeper in the navigation, the back view would not be the same as the root view.
这篇关于如何从推送的控制器中获取 RootViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从推送的控制器中获取 RootViewController?
基础教程推荐
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
