我正在开发一款iPhone应用程序,需要检查按钮是否被长按了6秒,并触发播放某种声音的操作。
我该如何检测这个6秒的长按事件?
另外,用户还可以持续点击按钮6秒钟,然后触发相同的操作。
对于多次点击,我该怎么办?如何确定所有的点击都在6秒内?
我正在开发一款iPhone应用程序,需要检查按钮是否被长按了6秒,并触发播放某种声音的操作。
我该如何检测这个6秒的长按事件?
另外,用户还可以持续点击按钮6秒钟,然后触发相同的操作。
对于多次点击,我该怎么办?如何确定所有的点击都在6秒内?
UILongPressGestureRecognizer
并将其 minimumPressDuration
属性设置为6。
编写自己的手势识别器(比如,LongTappingGestureRecognizer
)以进行给定时间段的连续点击操作; 这不应该太复杂。给它添加一个像 UILongPressGestureRecognizer
的属性minimumPressDuration
(例如,minimumTappingDuration
)和一个属性(例如,maximumLiftTime
),它确定手指离开多久之后不再被视为长按手势。
touchesBegan:withEvent:
时,记录时间。touchesEnded:withEvent:
时,启动一个 NSTimer
(上升计时器),在 maximumLiftTime
后向手势识别器发送取消消息(例如 cancelRecognition
)。touchesBegan:withEvent:
时,取消上升计时器(如果有的话)。cancelRecognition
将转换到 failed state。touchesBegan:withEvent:
和touchesEnded:withEvent:
处理程序中检查当前时间和开始时间之间的差是否>=minimumTappingDuration
。问题在于,如果用户轻敲屏幕且手指在达到minimumTappingDuration
时仍按下,则识别手势需要的时间将比minimumTappingDuration
长。另一种方法是在接收到第一个touchesBegan:withEvent:
时启动另一个NSTimer(识别计时器),该计时器将导致转换到recognized state并在cancelRecognition
中被取消。这里的棘手之处在于如果手指在计时器触发时抬起怎么办。最好的方法可能是两种方法的结合,如果手指抬起则忽略识别计时器。我意识到这是一个相当过时的问题,不过答案应该很简单。
在您的视图控制器viewDidLoad方法中:
//create long press gesture recognizer(gestureHandler will be triggered after gesture is detected)
UILongPressGestureRecognizer* longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandler:)];
//adjust time interval(floating value CFTimeInterval in seconds)
[longPressGesture setMinimumPressDuration:6.0];
//add gesture to view you want to listen for it(note that if you want whole view to "listen" for gestures you should add gesture to self.view instead)
[self.m_pTable addGestureRecognizer:longPressGesture];
[longPressGesture release];
那么在你的gestureHandler中:
-(void)gestureHandler:(UISwipeGestureRecognizer *)gesture
{
if(UIGestureRecognizerStateBegan == gesture.state)
{//your code here
/*uncomment this to get which exact row was long pressed
CGPoint location = [gesture locationInView:self.m_pTable];
NSIndexPath *swipedIndexPath = [self.m_pTable indexPathForRowAtPoint:location];*/
}
}
这是我的解决方案。
- (IBAction) micButtonTouchedDownAction {
self.micButtonTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(micButtonAction:) userInfo:nil repeats:YES];
self.micButtonReleased = FALSE;
}
- (IBAction) micButtonTouchedUpInsideAction {
self.micButtonReleased = TRUE;
}
- (IBAction) micButtonTouchedUpOutsideAction {
self.micButtonReleased = TRUE;
}
- (void) micButtonAction:(NSTimer *)timer {
[self.micButtonTimer invalidate];
self.micButtonTimer = nil;
if(self.micButtonReleased) {
NSLog(@"Tapped");
}
else {
NSLog(@"Touched");
}
}