iur*_*iur 3 uiviewcontroller ios uialertcontroller
我想在任何 UIAlertController 由于用户点击警报按钮之一而自行关闭(动画完成)之前和之后执行一些操作并呈现一些 UI。
我怎样才能收到用户按下 UIAlertController 中的某个按钮并且它将被解雇然后又被解雇的通知?
在文档中,建议不要子类化 UIAlertController。我仍然尝试过子类化,认为也许它内部会调用func dismiss(animated flag: Bool, completion: (() -> Void)? = nil)自己。类似的self.dismiss(...,不过iOS10上好像不是这样。
我还尝试将“手动”解雇添加到 UIAlertAction 处理程序中:
let alert = UIAlertController.init(...
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
alert.dismiss(animated: true, completion: {
print("Dismissed")
})
})
alert.addAction(defaultAction)
Run Code Online (Sandbox Code Playgroud)
但似乎警报在按下按钮后但在调用处理程序之前被解除。无论如何它也不太好用。即使它有效,记住将我的代码添加到每个 UIAlertAction 处理程序中也会有点麻烦。
我将不胜感激任何想法。
尽管不建议子类化,但您可以使用像这样的简单子类:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
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")
}
Run Code Online (Sandbox Code Playgroud)
输出按以下顺序排列:
| 归档时间: |
|
| 查看次数: |
2985 次 |
| 最近记录: |