当点击外部的UIAlertController时,如何排除UIAlertController?
我可以添加一个UIAlertAction of style UIAlertActionStyleCancel来取消UIAlertController。
但是我想添加一个函数,当用户点击UIAlertController外部时,UIAlertController就会关闭它。怎么做?谢谢。
发布于 2015-05-06 12:00:43
添加一个带有样式UIAlertActionStyleCancel的单独的取消操作。这样,当用户点击外部时,您将得到回调。
Obj-c
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"A Message" preferredStyle:UIAlertControllerStyleActionSheet];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
// Called when user taps outside
}]];Swift 5.0
let alertController = UIAlertController(title: "Alert Title", message: "A Message", preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {
action in
// Called when user taps outside
}))发布于 2016-04-12 08:46:53
如果您的目标设备的iOS > 9.3,并且使用Swift和preferredStyle is Alert,您可以使用以下代码片段:
func showAlertBtnClicked(sender: UIButton) {
let alert = UIAlertController(title: "This is title", message: "This is message", preferredStyle: .Alert)
self.presentViewController(alert, animated: true, completion:{
alert.view.superview?.userInteractionEnabled = true
alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped)))
})
}
func alertControllerBackgroundTapped()
{
self.dismissViewControllerAnimated(true, completion: nil)
}与迅捷3:
func showAlertBtnClicked(sender: UIButton) {
let alert = UIAlertController(title: "This is title", message: "This is message", preferredStyle: .alert)
self.present(alert, animated: true) {
alert.view.superview?.isUserInteractionEnabled = true
alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped)))
}
}
func alertControllerBackgroundTapped()
{
self.dismiss(animated: true, completion: nil)
}发布于 2018-03-30 13:45:50
Swift,Xcode 9
取消AlertController按钮
向您的alertController提供UIAlertAction的样式为.cancel的操作
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)使用这种方法,当用户点击“取消操作”按钮,以及在alertController之外时,alertController将被取消。
如果您不希望用户在alertController之外修改后拒绝使用alertController,那么在完成当前方法的闭包过程中,禁用alertController的第一个子视图的用户交互。
self.present(alertController, animated: true) {
alertController.view.superview?.subviews[0].isUserInteractionEnabled = false
}在Controller视图之外的触摸时取消AlertController
如果您不希望在控制器视图中取消按钮,并且希望在用户在控制器视图之外触摸时关闭控制器,请这样做。
self.present(alertController, animated: true) {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissAlertController))
alertController.view.superview?.subviews[0].addGestureRecognizer(tapGesture)
}
@objc func dismissAlertController(){
self.dismiss(animated: true, completion: nil)
}https://stackoverflow.com/questions/30075832
复制相似问题