如何为 UIViewController.view 中也有 UITapGestureRecognizer 的 UIView 挑出并操作 UITapGestureRecognizer?
How to single out and action a UITapGestureRecognizer for a UIView that is in the UIViewController.view that also has a UITapGestureRecognizer?
我有一个添加了 UITapGestureRecognizer 的 UIView 对象。主视图还有一个 UITapGestureRecognizer,我用它来隐藏键盘。我如何优先处理子 UIView 上的 tapGesture 来做我需要做的事情?我想在点击子视图时触发与此点击相关的操作,而不是主视图的手势。
我尝试在子视图中添加双击以区分这两种手势,但这只会触发主视图的点击操作。
var childView: UIView!
/**Tap screen event listener - to hide the keyboard*/
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(hideKeyBaord))
self.view.addGestureRecognizer(tapGesture)
let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(doSomethingElse))
doubleTap.numberOfTouchesRequired = 2
childView.view.addGestureRecognizer(doubleTap)
一种方法是为 tapGesture
实现 shouldReceiveTouch
委托方法:
extension YourViewController : UIGestureRecognizerDelegate {
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecogniser == tapGesture {
// tapGesture should not receive the touch when the touch is inside the child view
let location = touch.location(in: childView)
return !childView.bounds.contains(location)
} else {
return true
}
}
}
并记得将 tapGesture
的委托设置为 self
。
我有一个添加了 UITapGestureRecognizer 的 UIView 对象。主视图还有一个 UITapGestureRecognizer,我用它来隐藏键盘。我如何优先处理子 UIView 上的 tapGesture 来做我需要做的事情?我想在点击子视图时触发与此点击相关的操作,而不是主视图的手势。
我尝试在子视图中添加双击以区分这两种手势,但这只会触发主视图的点击操作。
var childView: UIView!
/**Tap screen event listener - to hide the keyboard*/
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(hideKeyBaord))
self.view.addGestureRecognizer(tapGesture)
let doubleTap = UITapGestureRecognizer.init(target: self, action: #selector(doSomethingElse))
doubleTap.numberOfTouchesRequired = 2
childView.view.addGestureRecognizer(doubleTap)
一种方法是为 tapGesture
实现 shouldReceiveTouch
委托方法:
extension YourViewController : UIGestureRecognizerDelegate {
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecogniser == tapGesture {
// tapGesture should not receive the touch when the touch is inside the child view
let location = touch.location(in: childView)
return !childView.bounds.contains(location)
} else {
return true
}
}
}
并记得将 tapGesture
的委托设置为 self
。