美文网首页程序员
iOS 获取当前页面的控制器

iOS 获取当前页面的控制器

作者: 枫developer | 来源:发表于2018-06-17 10:00 被阅读0次

    大家在开发的过程中,肯定会遇到一些情况,在一些工具类中需要获取当前页面的控制器。这里为大家提供一个方法方便大家使用:

    OC版本:

    #import "UIApplication+Extension.h"
    
    @implementation UIApplication (Extension)
    
    +(UIViewController *)topViewController:(UIViewController *)baseViewController {
        if (baseViewController == nil) {
            baseViewController = [[UIApplication sharedApplication] keyWindow].rootViewController;
        }
        
        if ([baseViewController isKindOfClass:[UINavigationController class]]) {
            return [UIApplication topViewController:((UINavigationController *)baseViewController).visibleViewController];
        }
        
        if ([baseViewController isKindOfClass:[UITabBarController class]]) {
            UIViewController *selectViewController = ((UITabBarController *)baseViewController).selectedViewController;
            if (selectViewController) {
                return [UIApplication topViewController:selectViewController];
            }
        }
        
        UIViewController *presentViewController = baseViewController.presentedViewController;
        if (presentViewController) {
            return [self topViewController:presentViewController];
        }
        
        return baseViewController;
    }
    
    @end
    

    Swift版本:

    import UIKit
    
    extension UIApplication {
        
        class func topViewController(_ baseViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
            if let navigationViewController = baseViewController as? UINavigationController {
                return topViewController(navigationViewController.visibleViewController)
            }
            
            if let tab = baseViewController as? UITabBarController {
                if let selected = tab.selectedViewController {
                    return topViewController(selected)
                }
            }
            
            if let presented = baseViewController?.presentedViewController {
                return topViewController(presented)
            }
            
            return baseViewController
        }
        
    }
    

    相关文章

      网友评论

        本文标题:iOS 获取当前页面的控制器

        本文链接:https://www.haomeiwen.com/subject/gdlyeftx.html