在 iPhone 上检测长按

7

我正在开发一款iPhone应用程序,需要检查按钮是否被长按了6秒,并触发播放某种声音的操作。

我该如何检测这个6秒的长按事件?

另外,用户还可以持续点击按钮6秒钟,然后触发相同的操作。

对于多次点击,我该怎么办?如何确定所有的点击都在6秒内?

3个回答

18
对于六秒钟的长按,使用 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中被取消。这里的棘手之处在于如果手指在计时器触发时抬起怎么办。最好的方法可能是两种方法的结合,如果手指抬起则忽略识别计时器。
细节还有更多,但这就是要点。基本上,它是一个长按识别器,允许用户将手指短暂地离开屏幕。您可以潜在地使用只有轻敲识别器并跳过长按识别器。

11

我意识到这是一个相当过时的问题,不过答案应该很简单。

在您的视图控制器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];*/
    }
}

对于此代码,值得一提的是,楼主指出了应该识别的两种情况。一种是单次长按(该代码可以检测到),另一种是在六秒内重复轻点屏幕(该代码无法检测到,我认为是这样的)。总之,上面的代码对于大多数人都很有用,他们只想知道如何设置最小长按要求。 - ToolmakerSteve

0

这是我的解决方案。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接