Objective-C非视图类如何获取当前视图控制器弹出UIAlertController
编译错误解决
首先你的编译报错是拼写错误导致:你将系统方法名presentViewController:animated:completion:误写为presetViewController:animated:completion:,修正拼写即可解决该编译问题。
弹窗弹出逻辑优化
直接使用rootViewController弹出弹窗存在潜在问题:如果当前rootViewController已经弹出了其他视图控制器,直接调用present会触发系统警告,甚至弹窗无法正常显示,建议先获取当前App最顶层的可视视图控制器后再执行弹出操作。
你可以添加一个工具方法获取顶层视图控制器:
+ (UIViewController *)fetchTopMostViewController { UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow; // 兼容iOS13及以上版本的keyWindow获取 if (@available(iOS 13.0, *)) { for (UIWindowScene *scene in [UIApplication sharedApplication].connectedScenes) { if (scene.activationState == UISceneActivationStateForegroundActive) { for (UIWindow *window in scene.windows) { if (window.isKeyWindow) { keyWindow = window; break; } } } } } UIViewController *topVC = keyWindow.rootViewController; while (topVC.presentedViewController) { topVC = topVC.presentedViewController; // 适配导航控制器、标签控制器的层级 if ([topVC isKindOfClass:[UINavigationController class]]) { topVC = [(UINavigationController *)topVC topViewController]; } else if ([topVC isKindOfClass:[UITabBarController class]]) { topVC = [(UITabBarController *)topVC selectedViewController]; } } return topVC; }
最终调用代码
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]]; // 调用工具方法获取顶层控制器后弹出 UIViewController *topVC = [YourUtilityClass fetchTopMostViewController]; // 替换为你存放工具方法的类名 [topVC presentViewController:alert animated:YES completion:nil];
内容的提问来源于stack exchange,提问作者Steve A
相关产品推荐
相关产品推荐

