在iPhone上检测长按

我正在开发一个iPhone应用程序,它需要我检查button是否被按下并保持按住6秒,然后触发正在播放某种声音的动作。

我应该如何检测这6秒的水龙头?

另一方面,用户也可以继续点击button6秒钟,然后同样的动作应该触发。

我应该怎么做多个水龙头,我怎么知道所有的水龙头都在6秒的支架下?

对于六秒钟的长按,使用UILongPressGestureRecognizer ,其minimumPressDuration属性设置为6。

编写你自己的手势识别器 (比如说, LongTappingGestureRecognizer )来持续点击一段时间; 它不应该太棘手。 给它一个属性,比如UILongPressGestureRecognizerminimumPressDuration (比如说minimumTappingDuration )和一个属性(比如说maximumLiftTime ),这个属性决定了一个手指在不被认为是一个长时间的敲击手势之前可以被提起多长时间。

  • 当它第一次收到touchesBegan:withEvent: ,logging时间。
  • 当它接收到touchesEnded:withEvent: ,启动一个NSTimer (提升定时器),它在maximumLiftTime之后向手势识别器发送取消消息(例如cancelRecognition )。
  • 当它收到touchesBegan:withEvent:当有一个开始时间,取消升降机定时器(如果有的话)。
  • cancelRecognition将转换到失败状态 。

在达到手势的末尾时,有minimumTappingDuration处理方式来识别手势的minimumTappingDuration 。 一个是检查touchesBegan:withEvent:touchesEnded:withEvent:处理程序,如果当前时间和开始时间之间的差异> = minimumTappingDuration 。 与此相关的问题是,如果用户正在慢慢地敲击,并且在达到minimumTappingDuration时,手指已经closures,则需要花费比minimumTappingDuration更长的时间来识别手势。 另一种方法是当接收到第一个touchesBegan:withEvent:时,启动另一个NSTimer(识别计时器),一个将导致转换到识别状态,并在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]; 

然后在你的手势处理器

 -(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];*/ } } 

这是我的解决scheme。

 - (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"); } }