我們在非視圖類中想要隨時展示一個view時白筹,需要將被展示的view加到當前view的子視圖悲龟,或需要 presentViewController,或pushViewContrller隐锭,這些操作都需要獲取當前正在顯示的ViewController晒杈。
發(fā)覺百度搜出來好多不科學(xué)的方法柑贞,有時候還是自己動腦子想好方椎。。凌外。
下面提供了一個公用的方法去獲取當前ViewController辩尊,也建議直接改成靜態(tài)方法涛浙,放到工具類里直接調(diào)用更加科學(xué)康辑。
具體代碼如下:
//獲取當前屏幕顯示的viewcontroller
- (UIViewController *)getCurrentVC
{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
return currentVC;
}
- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
UIViewController *currentVC;
if ([rootVC presentedViewController]) {
// 視圖是被presented出來的
rootVC = [rootVC presentedViewController];
}
if ([rootVC isKindOfClass:[UITabBarController class]]) {
// 根視圖為UITabBarController
currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
} else if ([rootVC isKindOfClass:[UINavigationController class]]){
// 根視圖為UINavigationController
currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
} else {
// 根視圖為非導(dǎo)航類
currentVC = rootVC;
}
return currentVC;
}
解析:代碼主要使用了遞歸的思想(哈哈哈,畢業(yè)工作半年轿亮,發(fā)覺第一次寫iOS用到遞歸疮薇,突然覺得高大上)。
[UIApplication sharedApplication].keyWindow.rootViewController獲取到的是項目的根視圖我注,結(jié)合可能用到UITabBarController或者UINavigationController作為導(dǎo)航結(jié)構(gòu)按咒,以及可能present出新的VC,其實如果用storyboard的方式寫UI的話就很清晰但骨,類似樹的結(jié)構(gòu)励七,再利用遞歸找到當前視圖。
ps:
如果是需要push新的視圖奔缠,就很簡單啦:
用上面的方法獲取到頂層的視圖掠抬,判斷currentVC.navigationController是否為nil。(為nil校哎,則新建UINavigationController在push两波;否則直接用currentVC.navigationController去push)
ps2:
補充評論里好的建議,如果用到的場景主要是vc里闷哆,可以弄成類別如下:
#import "UIViewController+Helper.h"
@property (nonatomic, strong ,readonly) UIViewController * _Nullable currentVC;
//當前屏幕顯示的viewcontroller
-(UIViewController *)currentVC{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *controller = [self getCurrentVCFrom:rootViewController];
return controller;
}
//getCurrentVCFrom參考上文
還有什么不懂的就留言問問哈腰奋。。抱怔。劣坊。