如何触摸UIAlertView外面的任何地方?

时间:2016-04-13 00:20:11

标签: ios swift uialertview

当用户触摸其范围之外的任何地方时,我需要关闭AlertView。

我知道你必须致电

alert.dismissViewControllerAnimated(true, completion: nil)

取消AlertView,但是只有当用户触摸除了视图中的一个按钮之外的任何地方时,我该怎么做?

这是史蒂夫建议后的代码:

presentViewController(alert, animated: true, completion: nil)
    //Add gesture recognizer for alert ViewController when adding an event
    let tapGesture = UITapGestureRecognizer(target: self, action: "alertClose:")
    view.addGestureRecognizer(tapGesture)
    //dismiss the alert if the user click anywhere except the buttons
    func alertClose(gesture: UITapGestureRecognizer) {
        alert.dismissViewControllerAnimated(true, completion: nil)
    }

1 个答案:

答案 0 :(得分:2)

当您使用如下所示的完成处理程序发出警报时:

self.presentViewController(alert, animated: true, completion:{
        alert.view.superview?.userInteractionEnabled = true
        alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertClose(_:))))
})

注意: Pre Swift 2.2替换

#selector(self.alertClose(_:))

Selector("alertClose")

然后创建警报关闭功能:

func alertClose(gesture: UITapGestureRecognizer) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

我在iPhone 6上使用swift 2.2进行了测试