我正在开发一个 iPhone 应用程序,它要求我检查是否已点击按钮并按住 6 秒,然后触发一个播放某种声音的动作。
我应该如何检测这个 6 秒的点击?
另一方面,用户还可以持续点击按钮 6 秒,然后会触发相同的操作。
我应该如何处理多次点击,我怎么知道所有点击都落在 6 秒括号内?
对于长按六秒,请使用UILongPressGestureRecognizer http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UILongPressGestureRecognizer_Class/Reference/Reference.html%23//apple_ref/occ/cl/UILongPressGestureRecognizer以其minimumPressDuration
属性设置为 6。
写你自己的手势识别器 https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizer_basics/GestureRecognizer_basics.html (say, LongTappingGestureRecognizer
) 在给定时间内连续攻丝;这应该不会太棘手。给它一个像这样的属性UILongPressGestureRecognizer
's minimumPressDuration
(say, minimumTappingDuration
)和一个属性(比如,maximumLiftTime
),它确定手指可以抬起多长时间才不被视为长敲击手势。
- 当它第一次收到touchesBegan:withEvent: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIGestureRecognizer_Class/Reference/Reference.html%23//apple_ref/occ/cl/UIGestureRecognizer,记录时间。
- 当它收到touchesEnded:withEvent: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIGestureRecognizer_Class/Reference/Reference.html%23//apple_ref/occ/cl/UIGestureRecognizer,开始一个NSTimer http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSTimer_Class/Reference/NSTimer.html(抬起计时器)向手势识别器发送取消消息(例如
cancelRecognition
) after maximumLiftTime
.
- 当它收到
touchesBegan:withEvent:
当有开始时间时,取消电梯计时器(如果有)。
- The
cancelRecognition
将过渡到失败状态 http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIGestureRecognizer_Class/Reference/Reference.html%23//apple_ref/c/econst/UIGestureRecognizerStateFailed.
有多种策略可以处理到达手势结束时的识别,之后minimumTappingDuration
。一种是同时检查touchesBegan:withEvent:
and touchesEnded:withEvent:
如果当前时间和开始时间之间的差异 >= 则处理程序minimumTappingDuration
。这样做的问题是,它需要的时间比minimumTappingDuration
如果用户缓慢点击并且手指向下,则识别手势minimumTappingDuration
到达了。另一种方法是在第一个 NSTimer(识别计时器)启动时启动另一个 NSTimer(识别计时器)。touchesBegan:withEvent:
收到,这将导致过渡到公认的状态 http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizers/GestureRecognizers.html并且被取消了cancelRecognition
。这里棘手的事情是,如果在计时器触发时手指被抬起该怎么办。最好的方法可能是两者的结合,如果手指抬起则忽略识别计时器。
还有更多细节,但这就是要点。基本上,它是一个长按识别器,可以让用户将手指短暂地离开屏幕。您可以只使用点击识别器并跳过长按识别器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)