在做项目时,有时候,会写一个工具类来对项目进行操作:
这个时候如果需要使用当前控制器去进行一些操作,比如想去present一个alertController,
这时候就需要获取到当前控制器了,下面就是获取的方法:根据每个App都是一个单例来获取当前窗口的根控制器,从而获取到所有的控制器,找到
+ (UIViewController *)getCurrentVC {
UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
if (!window) {
return nil;
}
UIView *tempView;
for (UIView *subview in window.subviews) {
if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
tempView = subview;
break;
}
}
if (!tempView) {
tempView = [window.subviews lastObject];
}
id nextResponder = [tempView nextResponder];
while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
tempView = [tempView.subviews firstObject];
if (!tempView) {
return nil;
}
nextResponder = [tempView nextResponder];
}
return (UIViewController *)nextResponder;
}
swift写法
class dynamic func getCurrentController() -> UIViewController? {
guard let window = UIApplication.shared.windows.first else {
return nil
}
var tempView: UIView?
for subview in window.subviews.reversed() {
if subview.classForCoder.description() == "UILayoutContainerView" {
tempView = subview
break
}
}
if tempView == nil {
tempView = window.subviews.last
}
var nextResponder = tempView?.next
var next: Bool {
return !(nextResponder is UIViewController) || nextResponder is UINavigationController || nextResponder is UITabBarController
}
while next{
tempView = tempView?.subviews.first
if tempView == nil {
return nil
}
nextResponder = tempView!.next
}
return nextResponder as? UIViewController
}
}