Ios 通过点击外部关闭UIAlertViewController
我想通过点击UIAlertViewController的外部,点击黑屏空间来关闭我的UIAlertViewController。我试过这个:Ios 通过点击外部关闭UIAlertViewController,ios,swift,uialertview,Ios,Swift,Uialertview,我想通过点击UIAlertViewController的外部,点击黑屏空间来关闭我的UIAlertViewController。我试过这个: self.presentViewController(alertViewController, animated: true, completion:{ alertViewController.view.superview?.userInteractionEnabled = true alertViewController.
self.presentViewController(alertViewController, animated: true, completion:{
alertViewController.view.superview?.userInteractionEnabled = true
alertViewController.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:))))
})
但如果我点击UIAlertViewController,它就会关闭。但我想在外面,半黑的屏幕敲打着
可能吗
更新
@IBAction func shareButtonTapped(sender: UIButton) {
let alertViewController = UIAlertController(title: "Share on social networks", message: "Where do you want to share?", preferredStyle: .ActionSheet)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissAlertView:")
self.view.addGestureRecognizer(tapGestureRecognizer)
let facebookAction = UIAlertAction(title: "Facebook", style: .Default) { (alert: UIAlertAction) -> Void in
}
let twitterAction = UIAlertAction(title: "Twitter", style: .Default) { (alert: UIAlertAction) -> Void in
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Destructive) { (alert: UIAlertAction) -> Void in
}
alertViewController.addAction(facebookAction)
alertViewController.addAction(twitterAction)
alertViewController.addAction(cancelAction)
self.presentViewController(alertViewController, animated: true, completion:{
alertViewController.view.superview?.userInteractionEnabled = true
alertViewController.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:))))
})
}
警报关闭功能:
func alertClose(gesture: UITapGestureRecognizer) {
self.dismissViewControllerAnimated(true, completion: nil)
}
uitappesturerecognizer
添加到UIWindow
类中
view.window.addgestureerecognizer()
应接收触摸屏
并检查您的视图希望此帮助如果您使用的是ActionSheet样式,则无需执行此操作。因为当你们点击半黑屏幕时,视图控制器会自动被解除 但如果要与警报样式一起使用,请执行以下操作(不带:alertViewController.view.superview?.userInteractionEnabled=true):
发布你的
alertClose
函数。我猜你是指UIAlertController?您可能需要将UIAlertController子类化,将GestureRecognizer委托设置为self,这样您就可以重写shouldReceiveTouchs:。这样,当触摸在主窗口上时,您可以返回false。这会给你想要的效果。@代码完成!我已经添加了我的代码的其他部分,已经用答案@mitulmarsonia提问,这些答案对我没有帮助=/
self.presentViewController(alertViewController, animated: true, completion: {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:)))
alertViewController?.view.superview?.addGestureRecognizer(tapGestureRecognizer)
})