在處理 URL Router 跳轉(zhuǎn)的時候坦胶,我們經(jīng)常需要得到 當(dāng)前最上層的視圖控制器 和 當(dāng)前最上層的導(dǎo)航控制器 來進行視圖跳轉(zhuǎn)或者方法調(diào)用坤邪。
一段代碼厌漂,隨取隨用号阿。當(dāng)然丟到 工具庫 之類的地方可以更加方便的使用。當(dāng)然要注意一下,如果寫類別捌蚊,不要跟別的方法沖突了集畅,這種坑誰踩誰知道。
- (UIViewController *)currentViewController
{
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIViewController *vc = keyWindow.rootViewController;
while (vc.presentedViewController)
{
vc = vc.presentedViewController;
if ([vc isKindOfClass:[UINavigationController class]])
{
vc = [(UINavigationController *)vc visibleViewController];
}
else if ([vc isKindOfClass:[UITabBarController class]])
{
vc = [(UITabBarController *)vc selectedViewController];
}
}
return vc;
}
- (UINavigationController *)currentNavigationController
{
return [self currentViewController].navigationController;
}