我正在使用警报控制器在捕获块中显示错误。 但是,在它自行消失之前,用户几乎看不到它。 我做错了什么? 这是我的代码。
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)
})
}
您的问题是self.dismiss(animated: true, completion: nil)
被调用在错误的位置。一旦你提出了_alertController,你就在调用这个。显示警报控制器后,实际上不需要调用它。UIAlertAction 处理关闭它。
我想通了!我误解了警报控制器的工作原理。 我以为它会阻塞线程,直到用户响应;它没有。 因此,此函数后面的代码正在关闭警报面板。
工作代码是在显示警报后返回 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
}
删除 self.dismiss(animated: true, complete: nil)