UIApplication keyWindow rootViewController 为 nil 的问题

本文探讨了UIAlertView在显示和消失过程中导致rootViewController变为nil的问题,并提供了解决方案,建议使用alertView:diddismissWithButtonAtIndex:方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般来说 [UIApplication sharedApplication].keyWindow.rootViewController 会在 appDelegate 中初始化,并且整个应用运行过程中都不会变。


所以在很多地方需要用 presentModelViewController 方法时,用这个 rootViewController 是很方便的,因为它相当于一个全局变量,无需再申请、释放。


但是本人在使用过程中发现有 rootViewController 被改为 nil 的情况。


分析后发现,当 UIAlertView 调用 show 方法后,rootViewController 会被改为 nil,当它 dismiss 后又改回去。而我需要用户在点击 alertview 上的按钮后再做

presentModelViewController 的操作。


解决方法:

不要使用 alertview delegate 中的 

- (void)alertView:clickedButtonAtIndex:

方法


而要用:

- (void)alertView:diddismissWithButtonAtIndex:

方法!

上述代码是在显示一个消息框,内容为"当前搜索条件下无仪器操作历史记录"。如果要让窗口位于屏幕中心,可以使用iOS的`UIAlertController`或者UIKit的`UIAlertView`来实现,并设置其约束为居中。以下是修改后的Swift代码示例: ```swift import UIKit let message = "当前搜索条件下无仪器操作历史记录。" let alert = UIAlertController(title: "", message: message, preferredStyle: .alert) // 设置提示框在屏幕中心 let center = UIApplication.shared.keyWindow?.center ?? CGPoint.zero alert.preferredContentSize = CGSize(width: alert.frame.width, height: alert.frame.height) alert.center = center // 如果需要添加按钮,例如"确定"按钮 let okAction = UIAlertAction(title: "确定", style: .default, handler: nil) alert.addAction(okAction) UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil) ``` 如果你使用的是Objective-C,可以参考类似的方式: ```objective-c #import <UIKit/UIKit.h> NSString *message = @"当前搜索条件下无仪器操作历史记录。"; UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert]; // 居中设置 CGPoint center = [[UIApplication sharedApplication].keyWindow center]; alert.preferredContentSize = CGSizeMake(alert.frame.size.width, alert.frame.size.height); alert.center = center; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]; [alert addAction:okAction]; [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil]; ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值