如何在触摸 UIAlertView 之外的任何地方时关闭它?
How to dismiss a UIAlertView when touching anywhere outside of it?
我需要在用户触摸范围之外的任何地方时关闭 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)
}
当您显示警报时,使用这样的完成处理程序调用它:
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 replace
#selector(self.alertClose(_:))
与
Selector("alertClose")
然后创建警报关闭函数:
func alertClose(gesture: UITapGestureRecognizer) {
self.dismissViewControllerAnimated(true, completion: nil)
}
我用 swift 2.2 在 iPhone 6
上测试了这个
我需要在用户触摸范围之外的任何地方时关闭 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)
}
当您显示警报时,使用这样的完成处理程序调用它:
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 replace
#selector(self.alertClose(_:))
与
Selector("alertClose")
然后创建警报关闭函数:
func alertClose(gesture: UITapGestureRecognizer) {
self.dismissViewControllerAnimated(true, completion: nil)
}
我用 swift 2.2 在 iPhone 6
上测试了这个