我使用alert控制器在catch块中显示错误。然而,在它自行消失之前,用户几乎看不到它。我做错了什么?这是我的代码。
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController is CancelInspectionViewController {
persistentContainer.viewContext.rollback()
self.dismiss(animated: true, completion: nil)
return false
} else if viewController is SubmitInspectionViewController {
do {
try persistentContainer.viewContext.save()
self.dismiss(animated: true, completion: nil)
} catch {
_alertController = UIAlertController(title: "Error Saving", message: error.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
_alertController.addAction(defaultAction)
present(_alertController, animated:true, completion: {
self.dismiss(animated: true, completion: nil)
})
}
发布于 2017-01-14 06:50:25
您的问题是在错误的位置调用了self.dismiss(animated: true, completion: nil)
。一旦您展示了_alertController,您就会调用它。一旦显示了警报控制器,您实际上就不需要调用此函数。UIAlertAction会处理将其驳回。
发布于 2017-01-14 08:02:46
我想通了!我误解了alert控制器是如何工作的。我以为它会阻塞线程,直到用户响应;但事实并非如此。因此,此函数后面的代码将关闭警告面板。
工作代码是在呈现警报后返回false。
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController is CancelInspectionViewController {
persistentContainer.viewContext.rollback()
self.dismiss(animated: true, completion: nil)
return false
} else if viewController is SubmitInspectionViewController {
do {
try persistentContainer.viewContext.save()
self.dismiss(animated: true, completion: nil)
} catch {
let alertController = UIAlertController(title: "Error Saving", message: error.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated:true, completion: nil)
return false
}
发布于 2017-01-14 06:48:18
删除self.dismiss(动画: true,完成: nil)
https://stackoverflow.com/questions/41644622
复制相似问题