题
如何可以追踪如iPhone触摸屏上持续2秒的事件。就像在Safari中保存图像的图像添加到一个UIWebView?
解决方案
创建与在视图的+scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
方法-touchesBegan:withEvent:
一个NSTimer,并且在-invalidate
取消它(使用-touchesEnded:withEvent:
)。如果该方法在被调用它的选择点,则用户对任何时间的观点认为他们的手指,你的计时器的时间间隔设置为。例如:
接口(.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
}
不隶属于 StackOverflow