開發(fā)項目過程中蚓挤,有需要獲取當(dāng)前正在展示的控制器的需求磺送。本來想用響應(yīng)鏈的思路來實現(xiàn)驻子,發(fā)現(xiàn)會有很多問題。后面發(fā)現(xiàn)可以通過控制器的入棧方式來解決這個問題册着。
1. 控制器入棧方式拴孤,示例代碼如下:
///獲取當(dāng)前活動的控制器
+ (UIViewController *)getCurrentActivityViewController {
UIWindow *window = [UIApplication sharedApplication].delegate.window;
NSLog(@"window level: %.0f", window.windowLevel);
if (window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow * tmpWin in windows) {
if (tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
//從根控制器開始查找
UIViewController *rootVC = window.rootViewController;
UIViewController *activityVC = nil;
while (true) {
if ([rootVC isKindOfClass:[UINavigationController class]]) {
activityVC = [(UINavigationController *)rootVC visibleViewController];
} else if ([rootVC isKindOfClass:[UITabBarController class]]) {
activityVC = [(UITabBarController *)rootVC selectedViewController];
} else if (rootVC.presentedViewController) {
activityVC = rootVC.presentedViewController;
} else if ([rootVC isKindOfClass:[RTContainerController class]]) {
activityVC = [(RTContainerController *)rootVC contentViewController];
} else {
break;
}
rootVC = activityVC;
}
return activityVC;
}
上面的代碼中的RTContainerController
是我們項目中用到的 RTRootNavigationController 框架,如果項目中沒有用到的可以把上面對應(yīng)判斷項去掉甲捏。
2. 響應(yīng)鏈的方式(有問題演熟,思路可以參考)
/// 獲取當(dāng)前活動的控制器
+ (UIViewController *)getCurrentActivityViewController {
UIViewController *result = nil;
UIWindow *window = [UIApplication sharedApplication].delegate.window;
NSLog(@"window level: %.0f", window.windowLevel);
if (window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow * tmpWin in windows) {
if (tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
//通過響應(yīng)鏈來找到當(dāng)前View的控制器
UIView *rootVCView = window.rootViewController.view;
UIView *lastView = [self getLastSubviewsWithView:rootVCView];
NSLog(@"lastView = %@", lastView);
id nextResponder = [lastView nextResponder];
while (nextResponder) {
if ([nextResponder isKindOfClass:[UIViewController class]]) {
break;
} else if ([nextResponder isKindOfClass:[UIView class]]) {
nextResponder = [nextResponder nextResponder];
} else if ([nextResponder isKindOfClass:[UIApplication class]]) {
nextResponder = nil;
break;
}
}
if (nextResponder != nil) {
result = nextResponder;
} else {
result = window.rootViewController;
}
NSLog(@"當(dāng)前最前面的活動的控制器是: %@", result);
return result;
}
/// 獲取View的最底層子View
+ (UIView *)getLastSubviewsWithView:(UIView *)view {
UIView *lastView = view;
NSMutableString *viewString = [NSMutableString string];
while (lastView.subviews.count != 0) {
[viewString appendFormat:@"%@=>", NSStringFromClass(lastView.class)];
lastView = lastView.subviews.lastObject;
}
[viewString appendFormat:@"%@", NSStringFromClass(lastView.class)];
NSLog(@"查找最底層的View的過程是: %@", viewString);
return lastView;
}