我如何追踪在iPhone屏幕上触摸2秒钟的事件?就像在Safari中保存添加到UIWebView的图像一样?
-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
}