在做項(xiàng)目時,有時候,會寫一個工具類來對項(xiàng)目進(jìn)行操作:
這個時候如果需要使用當(dāng)前控制器去進(jìn)行一些操作,比如想去present一個alertController,
這時候就需要獲取到當(dāng)前控制器了,下面就是獲取的方法:根據(jù)每個App都是一個單例來獲取當(dāng)前窗口的根控制器,從而獲取到所有的控制器,找到
+ (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
}
}