本文介紹了如何獲取根視圖控制器?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送ChatGPT賬號..
我需要一個根視圖控制器的實例.
I need an instance of root view controller.
我嘗試了這些方法:
UIViewController *rootViewController = (UIViewController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];
返回:null:
當(dāng)我嘗試獲取控制器數(shù)組時:
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.
如果我嘗試從導(dǎo)航控制器中獲取:
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 中設(shè)置的 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
這篇關(guān)于如何獲取根視圖控制器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!