我有一个没有按钮的 UIAlertController(我使用此警报作为请稍候一些数据加载消息),我在我的 View Controller 的 viewDidLoad 函数中显示。显示警报后,我运行一个从数据库中检索信息的函数,完成后我想解除警报,以便用户可以继续,但是警报似乎在运行后并未解除:
self.dismiss(animated: true, completion: nil)
我也尝试过将我的 uialertcontroller 作为参数传递给函数并运行以下行但没有成功:
alertController.dismiss(animated: false, completion: nil)
编辑:这是我的 viewDidLoad 函数以及应该解除警报的函数
override func viewDidLoad() {
super.viewDidLoad()
let alertController = UIAlertController(title: "Loading", message:
"This might take a moment", preferredStyle: UIAlertControllerStyle.alert)
self.present(alertController, animated: true, completion: nil)
hideAlert(alert: alertController)
}
func hideAlert(alert: UIAlertController) {
let hideAlertController = { () -> Void in
alertController.dismiss(animated: false, completion: nil)
}
FIRDatabase.database().reference().child("info").observeSingleEvent(of: .value, with: { (dataSnapshot) in
DispatchQueue.main.async {
hideAlertController()
}
})
}
最佳答案
在你的 ViewController 中试试这个:
var operationPerformed : Bool = false;
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad();
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
if(!self.operationPerformed){
let alertController = UIAlertController(title: "Loading", message:
"This might take a moment", preferredStyle: UIAlertControllerStyle.alert);
self.present(alertController, animated: true, completion: nil);
self.performOperation(alertToBeClosedOnFinish: alertController);
}
}
func performOperation(alertToBeClosedOnFinish: UIAlertController) {
let hideAlertController = { () -> Void in
alertToBeClosedOnFinish.dismiss(animated: false, completion: nil)
}
DispatchQueue.global().asyncAfter(deadline: .now() + 2, execute: {
DispatchQueue.main.async {
hideAlertController();
self.operationPerformed = true;
}
});
}
想法是当它的所有者在层次结构中时显示警报 Controller ,如果我理解你的意思 - 你想调用它一次,所以你应该检查操作是否已经执行。
但这种方法的缺点是当您可以将进度 View 创建为 UIView 的子类并将其添加到 super View 或从 super View 中删除时,尝试使用警报 Controller 。此外,有很多 pod 可以帮助您实现这一目标。
最好的问候, 谢尔盖
关于ios - 无法从单独的函数中解雇 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43059266/