通过点击外部关闭 UIAlertViewController
Posted
技术标签:
【中文标题】通过点击外部关闭 UIAlertViewController【英文标题】:Dismiss UIAlertViewController by tapping outside 【发布时间】:2016-06-22 12:51:42 【问题描述】:我想通过在 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)
【问题讨论】:
发布您的alertClose
功能。
我猜你的意思是 UIAlertController?您可能需要继承 UIAlertController,将 GestureRecognizer 委托设置为 self,然后您可以覆盖 shouldReceiveTouches:。这样,当触摸在主窗口上方时,您可以返回 false。这应该会给你想要的效果。
@代码完成!我添加了代码的其他部分
已经提出问题并回答HERE.
@mitulmarsonia 那些答案对我没有帮助 =/
【参考方案1】:
如果您使用的是 ActionSheet 样式,则无需这样做。因为当您点击半黑屏时,视图控制器会自动被关闭。
但如果你想使用警报样式,请执行以下操作(没有: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)
)
【讨论】:
【参考方案2】:尝试将UITapGestureRecognizer
添加到您的UIWindow
类中,例如
view.window.addGestureRecognizer()
实现 UIGestureRecognizerDelegate 方法shouldReceiveTouch
并检查您点击的视图
希望有帮助
【讨论】:
以上是关于通过点击外部关闭 UIAlertViewController的主要内容,如果未能解决你的问题,请参考以下文章
IOS UI popoverController 在设备方向更改后不会通过点击外部来关闭
如何通过单击外部来关闭 Twitter Bootstrap 弹出窗口?