我想通过使用WKTapGestureRecognizer在watchOS上检测类似于“touchesBegan”和“touchesEnded”的状态。 但是下面的代码总是返回状态3(触摸结束)。
- (IBAction)handleGesture:(WKTapGestureRecognizer*)gestureRecognizer{
NSLog(@":%ld",(long)gestureRecognizer.state);}
你能告诉我如何检测1号和2号国家。
答案 0 :(得分:0)
正如official documentation中所述,WKTapGestureRecognizer是一个离散手势识别器,这意味着只有当它完成识别它时才会触发它,即在用户快速点击然后加注之后他的手指。
要从识别器接收多个状态更改,您必须使用连续识别器,例如WKLongPressGestureRecognizer(PanGesture并不是很有效):如果设置的值非常低minimumPressDuration
- 例如0.1秒 - 你可以欺骗它的行为类似于点击识别器,如下所示:
@IBAction func onRecognizerStateChange(_ recognizer: WKLongTapGestureRecognizer) {
switch recognizer.state {
case .began:
print("User just touched the screen, finger is still resting")
case .ended:
print("User has raised his finger")
default:
break
}
}
请记住,无论allowableMovement
属性值如何,在识别器转换到Begin状态后,仍然允许用户拖动手指,如果您正在尝试,这可能是不可取的检测简单的水龙头。要解决此问题,您可以在识别器切换到Begin状态时存储初始触摸位置,然后检查每次Changed状态回调时触摸是否移动得太远,如下例所示:
private var touchLocation = CGPoint.zero
@IBAction func onRecognizerStateChange(_ recognizer: WKLongTapGestureRecognizer) {
switch recognizer.state {
case .began:
touchLocation = recognizer.locationInObject()
print("User just touched the screen at \(touchLocation)")
case .changed:
let location = recognizer.locationInObject()
let distance = sqrt(pow(touchLocation.x - location.x, 2.0)
+ pow(touchLocation.y - location.y, 2.0))
if distance >= 10 {
print("User traveled too far from \(touchLocation)")
// invalidate the gesture recognizer
recognizer.isEnabled = false
recognizer.isEnabled = true
}
case .ended:
print("User successfully completed a tap-like gesture")
default:
break
}
}