如何在 iPhone 上追踪手指的长按?

4

我如何追踪在iPhone屏幕上触摸2秒钟的事件?就像在Safari中保存添加到UIWebView的图像一样?

1个回答

10
在视图的-touchesBegan:withEvent:方法中使用+scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:创建一个NSTimer,然后在-touchesEnded:withEvent:中取消它(使用-invalidate)。如果该方法所指向的选择器被调用,则表示用户按下手指并保持在视图上的时间长达您设置的计时器间隔。示例代码如下:

接口文件(.h):

@interface MyView : UIView
    ...
    NSTimer *holdTimer;
@end

实现 (.m):

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)evt
{
    [holdTimer invalidate];
    holdTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(touchWasHeld) userInfo:nil repeats:NO];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)evt
{
    [holdTimer invalidate];
    holdTimer = nil;
}

- (void)touchWasHeld
{
    holdTimer = nil;
    // do your "held" behavior here
}

1
这就是我在游戏中所做的。效果很好。 - Stefan Arentz

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