1. 程式人生 > >iOS 獲取當前螢幕顯示的viewcontroller

iOS 獲取當前螢幕顯示的viewcontroller

if (![[[self getCurrentVC] class] isEqual:[MineMessageViewController class]])
//獲取當前螢幕顯示的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 {
        // 根檢視為非導航類
        currentVC = rootVC;
    }
    return currentVC;
}