我想在点击黑屏空间时通过点击UIAlertViewController外部来解雇我的UIAlertViewController。我试过这个:
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(_:))))
})
}
AlertClose函数:
func alertClose(gesture: UITapGestureRecognizer) {
self.dismissViewControllerAnimated(true, completion: nil)
}
答案 0 :(得分:1)
如果您使用的是ActionSheet样式,则无需执行此操作。因为当你点击半黑屏时,控制器会自动被取消。
但如果您想使用Alert样式,请执行以下操作(不使用:alertViewController.view.superview?.userInteractionEnabled = true):
self.presentViewController(alertViewController, animated: true, completion: {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:)))
alertViewController?.view.superview?.addGestureRecognizer(tapGestureRecognizer)
})
答案 1 :(得分:0)
尝试将UITapGestureRecognizer
添加到您的UIWindow
课程中
view.window.addGestureRecognizer()
实现UIGestureRecognizerDelegate方法shouldReceiveTouch
并检查您的点击视图
希望这个帮助