iOS -获取栈顶控制器(Swift + OC版本)
2016-12-15 本文已影响767人
valentizx
即获取当前显示的控制器
适用Swift 3.0(此段写于 2016/12/15)
给UIViewController建了分类
class func currentViewController() -> UIViewController {
let vc = UIApplication.shared.keyWindow?.rootViewController
return UIViewController.findBestViewController(vc: vc!)
}
private class func findBestViewController(vc : UIViewController) -> UIViewController {
if vc.presentedViewController != nil {
return UIViewController.findBestViewController(vc: vc.presentedViewController!)
} else if vc.isKind(of:UISplitViewController.self) {
let svc = vc as! UISplitViewController
if svc.viewControllers.count > 0 {
return UIViewController.findBestViewController(vc: svc.viewControllers.last!)
} else {
return vc
}
} else if vc.isKind(of: UINavigationController.self) {
let nvc = vc as! UINavigationController
if nvc.viewControllers.count > 0 {
return UIViewController.findBestViewController(vc: nvc.topViewController!)
} else {
return vc
}
} else if vc.isKind(of: UITabBarController.self) {
let tvc = vc as! UITabBarController
if (tvc.viewControllers?.count)! > 0 {
return UIViewController.findBestViewController(vc: tvc.selectedViewController!)
} else {
return vc
}
} else {
return vc
}
}
在外部调用UIView.currentViewController
即可,打印结果:
简单粗暴的直接获取控制器类名需要type
函数:type(of: UIViewController.currentViewController().self)
打印结果:
对应OC版本(同样是建了分类):
+(UIViewController*)findBestViewController:(UIViewController*)vc
{
if (vc.presentedViewController) {
return [UIViewController findBestViewController:vc.presentedViewController];
} else if ([vc isKindOfClass:[UISplitViewController class]])
{
UISplitViewController* svc = (UISplitViewController*)vc;
if (svc.viewControllers.count > 0) {
return [UIViewController findBestViewController:svc.viewControllers.lastObject];
} else {
return vc;
}
} else if ([vc isKindOfClass:[UINavigationController class]])
{
UINavigationController* nvc = (UINavigationController*)vc;
if (nvc.viewControllers.count > 0) {
return [UIViewController findBestViewController:nvc.topViewController];
} else {
return vc;
}
} else if ([vc isKindOfClass:[UITabBarController class]])
{
UITabBarController* tvc = (UITabBarController*)vc;
if (tvc.viewControllers.count) {
return [UIViewController findBestViewController:tvc.selectedViewController];
} else {
return vc;
}
} else {
return vc;
}
}
+(UIViewController *)currentViewController
{
UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
return [UIViewController findBestViewController:viewController];
}