检测iPhone上的长按

Asa*_*han 7 iphone cocoa-touch objective-c uikit ios

我正在制作一个iPhone应用程序,它要求我检查按钮是否已被按下并按住6秒钟然后发出正在播放某种声音的动作.

我该如何检测这6秒钟?

另一方面,用户也可以继续点击按钮6秒钟然后应该触发相同的动作.

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

out*_*tis 18

对于长按六秒钟,请使用UILongPressGestureRecognizerminimumPressDuration属性设置为6的a.

编写自己的手势识别器(例如LongTappingGestureRecognizer),以便在给定时间内连续点击; 它不应该太棘手.给它像一个属性UILongPressGestureRecognizerminimumPressDuration(比如minimumTappingDuration)和属性(比如,maximumLiftTime确定了多久,它不被认为是一个长期的触击手势手指可以解除掉).

  • 首次收到时touchesBegan:withEvent:,记录时间.
  • 当它接收时touchesEnded:withEvent:,启动NSTimer(提升计时器),其向手势识别器发送取消消息(例如cancelRecognition)之后maximumLiftTime.
  • 当它touchesBegan:withEvent:在有一个开始时间时收到,取消提升计时器(如果有的话).
  • cancelRecognition将过渡到故障状态.

有各种策略用于处理识别何时到达手势的结束minimumTappingDuration.一种是检查当前时间和开始时间之间的差值是否大于touchesBegan:withEvent:touchesEnded:withEvent:处理程序minimumTappingDuration.这样做的问题是,minimumTappingDuration如果用户正在慢慢地敲击并且在minimumTappingDuration到达时手指向下,则识别手势将花费更长时间.另一种方法是在touchesBegan:withEvent:收到第一个NSTimer时启动另一个NSTimer(识别计时器),一个将导致转换到已识别状态并且在cancelRecognition.这里最棘手的事情是如果在计时器开火时手指被抬起该怎么办.最好的方法可能是两者的组合,如果手指被抬起则忽略识别计时器.

细节还有更多,但这就是要点.基本上,它是一种长按识别器,可让用户将手指从屏幕上抬起一小段时间.您可能只使用点击识别器并跳过长按识别器.


hri*_*.to 11

我意识到这是一个过时的问题,但答案应该很简单.

在View控制器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];
Run Code Online (Sandbox Code Playgroud)

然后在你的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];*/
    }
}
Run Code Online (Sandbox Code Playgroud)