在需要從非頁面context(例如網路回呼、單例類別)跳出提示框或做跳轉時,第一個要解決的問題永遠是:目前最前面的那個 ViewController 是誰?這裡整理兩種常見取法。
如果專案有固定的根結構(例如 TabBarController 包 NavigationController),沿著鏈一路取到底即可:
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
UIViewController *topViewController =
appdelegate.baseTabBarController.navigationController.topViewController;
NSLog(@"%@", topViewController);
if ([topViewController isKindOfClass:[HomeViewController class]]) {
// 針對特定頁面處理
}
若想寫成通用工具、不依賴 AppDelegate 的具體結構,可以從 keyWindow 往下找。這裡先避開 alert 等非正常層級的 window,再依序嘗試 rootView 的 nextResponder 與 window.rootViewController:
- (UIViewController *)getCurrentRootViewController {
UIViewController *result = nil;
// 找出最上層且層級為 Normal 的 window
UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
if (topWindow.windowLevel != UIWindowLevelNormal) {
for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
if (window.windowLevel == UIWindowLevelNormal) {
topWindow = window;
break;
}
}
}
UIView *rootView = [[topWindow subviews] objectAtIndex:0];
id nextResponder = [rootView nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
result = nextResponder;
} else if ([topWindow respondsToSelector:@selector(rootViewController)] &&
topWindow.rootViewController != nil) {
result = topWindow.rootViewController;
} else {
NSAssert(NO, @"找不到 root view controller,請手動指定");
}
return result;
}
更現代的寫法是用 UIScreen 或應用程式的 connectedScenes 取得 active window,再沿著 presentedViewController 鏈一路往下走到最後一個被 present 出來的控制器——那才是真正的「最上層」。上面這種 keyWindow 取法在多 window 場景(例如 iPad 分屏)容易出錯,新版專案建議改用 Scene 相關 API。