应用程序不显示警报视图控制器?
Application doesn't show Alert View Controller?
我有一个应用程序应该在 viewDidLoad() 函数中打开一个警报视图控制器。这是一个简单的提醒应用程序。这是一段代码:
let alert = UIAlertController(title: "Reminder", message: "Your reminder text", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Sure!", style: UIAlertActionStyle.default) {
(finished) in
self.didReceiveRemoteNotificationAction()
})
self.present(alert, animated: true, completion: nil)
但问题是:它没有出现!谁能给我解释一下为什么?
我知道我的 Storyboard 非常......与视图交错。但这应该不是问题,对吧?
当 viewDidLoad
被触发时,视图控制器的视图还不在 window 层次结构中,这就是为什么你的警报没有被显示的原因。
您应该将警报显示代码放在 viewDidAppear
而不是 viewDidLoad
。
这篇 讨论了同样的问题并解释了使用 GCD 的替代选项。
这个answer对viewDidLoad
和viewDidAppear
进行了很好的讨论。
祝你好运!
那是因为您是从 ViewDidLoad 调用它,您的视图尚未设置!您有两个选择:
- 从 ViewDidAppear 调用它(建议)。
使用 GCD 线程调用它:
DispatchQueue.main.async{
self.present(警报,动画:真,完成:无)
}
我有一个应用程序应该在 viewDidLoad() 函数中打开一个警报视图控制器。这是一个简单的提醒应用程序。这是一段代码:
let alert = UIAlertController(title: "Reminder", message: "Your reminder text", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Sure!", style: UIAlertActionStyle.default) {
(finished) in
self.didReceiveRemoteNotificationAction()
})
self.present(alert, animated: true, completion: nil)
但问题是:它没有出现!谁能给我解释一下为什么?
我知道我的 Storyboard 非常......与视图交错。但这应该不是问题,对吧?
当 viewDidLoad
被触发时,视图控制器的视图还不在 window 层次结构中,这就是为什么你的警报没有被显示的原因。
您应该将警报显示代码放在 viewDidAppear
而不是 viewDidLoad
。
这篇
这个answer对viewDidLoad
和viewDidAppear
进行了很好的讨论。
祝你好运!
那是因为您是从 ViewDidLoad 调用它,您的视图尚未设置!您有两个选择:
- 从 ViewDidAppear 调用它(建议)。
使用 GCD 线程调用它:
DispatchQueue.main.async{ self.present(警报,动画:真,完成:无) }