我需要一个根视图控制器的实例.
I need an instance of root view controller.
我尝试了这些方法:
UIViewController *rootViewController = (UIViewController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];
返回:null:
当我尝试获取控制器数组时:
Also when I try to get an array of controllers:
NSArray *viewControllers = self.navigationController.viewControllers;
它只返回一个控制器,但它不是我的根视图控制器.
It returns only one controller, but it isn't my root view controller.
如果我尝试从导航控制器中获取:
If I try to take from navigation controller:
UIViewController *root = (UIViewController*)[self.navigationController.viewControllers objectAtIndex:0];
返回:null:
任何想法为什么?我还能尝试获取根视图控制器的实例吗?
Any ideas why? What else could I try to get an instance of my root view controller?
谢谢.
如果您尝试访问您在 appDelegate 中设置的 rootViewController.试试这个:
if you are trying to access the rootViewController you set in your appDelegate. try this:
Objective-C
YourViewController *rootController = (YourViewController*)[[(YourAppDelegate*)
[[UIApplication sharedApplication]delegate] window] rootViewController];
斯威夫特
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController
斯威夫特 3
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! YourViewController
斯威夫特 4 &4.2
let viewController = UIApplication.shared.keyWindow!.rootViewController as! YourViewController
斯威夫特 5 &5.1 &5.2
let viewController = UIApplication.shared.windows.first!.rootViewController as! YourViewController
这篇关于如何获取根视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
KIF:如何自动运行/压力测试 iOS 应用程序以找出罕KIF: How to auto-run/stress test an iOS app to find the cause of a rare UI bug?(KIF:如何自动运行/压力测试 iOS 应用程序以找出罕见 UI 错
无法更改 Xcode 4.5 中的目标成员身份可见性Can#39;t change target membership visibility in Xcode 4.5(无法更改 Xcode 4.5 中的目标成员身份可见性)
UITableView:在混合单元格表视图静态和动态单元格UITableView: Handle cell selection in a mixed cell table view static and dynamic cells(UITableView:在混合单元格表视图静态和动态单元格中
如何在 iOS 中删除 Safari 中的地址栏?How to remove Address Bar in Safari in iOS?(如何在 iOS 中删除 Safari 中的地址栏?)
升级到 Xcode 4.5 后,iOS 5 SDK 消失了iOS 5 SDK is gone after upgrade to Xcode 4.5(升级到 Xcode 4.5 后,iOS 5 SDK 消失了)
在 iOS5 中从 CIImage 创建 UIImage 时遇到问题Having trouble creating UIImage from CIImage in iOS5(在 iOS5 中从 CIImage 创建 UIImage 时遇到问题)