iOS手势问题 - 如何检测在特定时间间隔内保持触摸的触摸事件?

时间:2011-05-15 08:36:28

标签: iphone ios ipad gesture

我在iOS中的触摸事件和手势方面都很新。

我需要在用户手指触摸特定时间间隔(如3秒)时触发事件。如何监控这种长按事件?

如果您能给我一些代码供参考,请欣赏它吗?

感谢。

2 个答案:

答案 0 :(得分:2)

你可以这样做。

在你.h文件中:

NSTimer *touchesHoldTimer;

@property (nonatomic, retain) NSTimer *touchesHoldTimer;

- (void)touchesHoldCheckTime;

请记住合成并发布touchesHoldTimer

在您的.m文件中:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *countTouches = [event allTouches];

    NSLog(@"touchesBegan");

    if ([countTouches count] == 1) { // Not multitouch
        NSLog(@"Starting timer..");

        touchesHoldTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(touchesHoldCheckTime) userInfo:nil repeats:NO];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesEnded");

    if (touchesHoldTimer != nil) {
        [touchesHoldTimer invalidate];
        touchesHoldTimer = nil;
    }
}

- (void)touchesHoldCheckTime {
    NSLog(@"You have hold me down for 3 sec.");

    [touchesHoldTimer invalidate];
    touchesHoldTimer = nil;
}

答案 1 :(得分:2)

您可能希望查看UILongPressGestureRecognizer是否适合您的应用程序界面。上面的Apple文档有一个示例代码链接。 UIView只提供四种覆盖方法。您可以使用手势识别器进行更多操作。 Here's其他手势识别器的示例代码。希望这会有所帮助。