开发者

iOS gesture problem - how to detect a touch event which keeps touching for certain time interval?

I am quite new in touch events and gestures in iOS.

I need to trigger an event when a user keep his finger touching for certain time interval like 3 seconds. How to开发者_开发知识库 monitor this kind of long press event ?

Appreciate it if you could give me some code for reference ?

Thanks.


You can do it like this.

In you .h file:

NSTimer *touchesHoldTimer;

And:

@property (nonatomic, retain) NSTimer *touchesHoldTimer;

- (void)touchesHoldCheckTime;

Remember to synthesize and release touchesHoldTimer

In your .m file:

- (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;
}


You probably want to look if the UILongPressGestureRecognizer suits for your application interface. The apple documentation above has a sample code link. UIView provides only four methods to override. You can do a bit more with gesture recognizers. Here's the sample code for other gesture recognizers. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜