如何获取根视图控制器?

2023-03-25移动开发问题
2

本文介绍了如何获取根视图控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要一个根视图控制器的实例.

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

这篇关于如何获取根视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

Cocos2d - 如何检查不同层中对象之间的交集
Cocos2d - How to check for Intersection between objects in different layers(Cocos2d - 如何检查不同层中对象之间的交集)...
2024-08-12 移动开发问题
8

如何将 32 位 PNG 转换为 RGB565?
How to convert 32 bit PNG to RGB565?(如何将 32 位 PNG 转换为 RGB565?)...
2024-08-12 移动开发问题
21

正确的 cocos2d 场景重启?
Proper cocos2d scene restart?(正确的 cocos2d 场景重启?)...
2024-08-12 移动开发问题
7

游戏中心 facebook 喜欢
Game center facebook like(游戏中心 facebook 喜欢)...
2024-08-12 移动开发问题
3

Objective-C++ 导入 C++ 类失败,未找到 cassert
Objective-C++ importing C++ class fails, cassert not found(Objective-C++ 导入 C++ 类失败,未找到 cassert)...
2024-08-12 移动开发问题
10