【发布时间】:2019-04-26 17:02:08
【问题描述】:
我正在尝试在我的应用上发出警报,但它不断给我如下警告并且它没有出现
Warning: Attempt to present <UIAlertController: 0x..> on <xyz.VC1: 0x..> whose view is not in the window hierarchy!
逻辑是这样的:-
(VC1) 中的IBAction 调用公共函数(X)
(X) 该函数执行一些操作和功能,并以此为基础称为公共函数(Alert)
(Alert) 该函数应该显示一个警报,但它给了我之前的警告。
注意:如果我直接从 IBAction 中使用警报,它会正常工作
显示警报:
func WAlert(){
// print("Wrong :("") // to be an alert
let alert = UIAlertController(title: "S?", message: "Y", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "C", style: UIAlertAction.Style.default, handler: { _ in
//Cancel Action
}))
alert.addAction(UIAlertAction(title: "out",
style: UIAlertAction.Style.default,
handler: {(_: UIAlertAction!) in
//Sign out action
}))
present(alert, animated: true, completion: nil)
//self.present(alert, animated: true, completion: nil)
//VC1.present(alert, animated: true, completion: nil)
【问题讨论】:
-
请添加您如何呈现警报的代码。
-
你能告诉我们使用的代码吗?另外,调用这个公共函数是否涉及任何异步线程?您是否尝试过在 VC1 中定义函数并以这种方式调用它?
-
您只能在用户可见的视图控制器上显示警报。
-
它会这样工作,但我试图避免“意大利面条代码”,我试图使代码简单且易于维护和编辑以进行进一步更新,这就是为什么我创建一个单独的“功能”“视图”“警报”...等文件
-
您可能调用它为时过早。除非正在呈现的控制器已经出现,否则您不能呈现控制器。这意味着您不能从
viewDidLoad或viewWillAppear展示它。只有在调用了viewDidAppear之后,您才能从self呈现控制器。
标签: ios swift uialertcontroller ibaction