由于用户点击其中一个警报按钮,我想在任何UIAlertController解散自身(动画完成)之前和之后立即执行一些操作并显示一些UI。
如何通知用户在我的UIAlertController中按下了某个按钮,它将被解雇然后被解雇?
在docs中建议不要继承UIAlertController。我仍然尝试过我的运气子类化,认为它可能在内部调用func dismiss(animated flag: Bool, completion: (() -> Void)? = nil)
。像self.dismiss(...
这样的东西,但在iOS10上似乎并非如此。
我还尝试在UIAlertAction处理程序中添加'manual'解雇:
let alert = UIAlertController.init(...
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
alert.dismiss(animated: true, completion: {
print("Dismissed")
})
})
alert.addAction(defaultAction)
但似乎警告在按下按钮之后但在调用处理程序之前被解雇。无论如何它不起作用。即使它有效,记住将我的代码添加到每个UIAlertAction处理程序中也会有点麻烦。
我很感激任何想法。
答案 0 :(得分:1)
虽然不建议使用子类,但您可以使用这样的简单子类:
class CustomAlertController: UIAlertController {
var willDisappearBlock: ((UIAlertController) -> Void)?
var didDisappearBlock: ((UIAlertController) -> Void)?
override func viewWillDisappear(_ animated: Bool) {
willDisappearBlock?(self)
super.viewWillDisappear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
didDisappearBlock?(self)
}
}
然后你可以像这样使用它:
let alert = CustomAlertController(title: "Alert", message: "This is an alert. Press Yes or No.", preferredStyle: .alert)
alert.willDisappearBlock = { alert in
print("\(alert) will disappear")
}
alert.didDisappearBlock = { alert in
print("\(alert) did disappear")
}
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (yesAction) in
print("User tapped Yes.")
}))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { (yesAction) in
print("User tapped No.")
}))
present(alert, animated: true) {
print("presentCompletion")
}
输出按以下顺序排列: