Swift:同时平移和长按识别器
Swift: Pan & LongPress Recognizers Simultanously
我在 viewController class 级别定义了 longPress 和平移手势识别器,如下所示:
var touch = UILongPressGestureRecognizer()
var pan = UIPanGestureRecognizer()
然后我创建一个简单的 UIView:
let qBox = UIView()
qBox.frame = CGRect(x: 100, y: 200, width: 50, height: 50)
self.view.addSubview(qBox)
然后我配置并添加我的识别器:
touch.addTarget(self, action: "ourTouched:")
touch.minimumPressDuration = 0
touch.numberOfTouchesRequired = 1
touch.numberOfTapsRequired = 0
qBox.addGestureRecognizer(touch)
pan.addTarget(self, action:"pan:")
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
self.view.addGestureRecognizer(pan)
现在,当我触摸 qBox UIView 时,它会触发 "ourTouched" 方法,但如果我一直按住然后开始平移,它不会拖动 qBox UIView。我尝试在我的 "ourTouched" 函数中添加以下行,以便在用户触摸 qBox UIView 时立即删除长按识别器:
qBox.removeGestureRecognizer(touch)
但是,在第一次触摸和拖动时,只会调用长按方法。我必须放手,然后重新开始平移。我错过了什么?
将 UIGestureRecognizerDelegate
添加到您的识别器,并将其 return YES
添加到 shouldRecognizeSimultaneously
。
{
// setup ...
touch.delegate = self
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return (gestureRecognizer == touch && otherGestureRecognizer == pan)
}
更新:Swift 4 或更高版本
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return (gestureRecognizer == touch && otherGestureRecognizer == pan)
}
我在 viewController class 级别定义了 longPress 和平移手势识别器,如下所示:
var touch = UILongPressGestureRecognizer()
var pan = UIPanGestureRecognizer()
然后我创建一个简单的 UIView:
let qBox = UIView()
qBox.frame = CGRect(x: 100, y: 200, width: 50, height: 50)
self.view.addSubview(qBox)
然后我配置并添加我的识别器:
touch.addTarget(self, action: "ourTouched:")
touch.minimumPressDuration = 0
touch.numberOfTouchesRequired = 1
touch.numberOfTapsRequired = 0
qBox.addGestureRecognizer(touch)
pan.addTarget(self, action:"pan:")
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
self.view.addGestureRecognizer(pan)
现在,当我触摸 qBox UIView 时,它会触发 "ourTouched" 方法,但如果我一直按住然后开始平移,它不会拖动 qBox UIView。我尝试在我的 "ourTouched" 函数中添加以下行,以便在用户触摸 qBox UIView 时立即删除长按识别器:
qBox.removeGestureRecognizer(touch)
但是,在第一次触摸和拖动时,只会调用长按方法。我必须放手,然后重新开始平移。我错过了什么?
将 UIGestureRecognizerDelegate
添加到您的识别器,并将其 return YES
添加到 shouldRecognizeSimultaneously
。
{
// setup ...
touch.delegate = self
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return (gestureRecognizer == touch && otherGestureRecognizer == pan)
}
更新:Swift 4 或更高版本
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return (gestureRecognizer == touch && otherGestureRecognizer == pan)
}