在我的应用程序中,我想创建一个自定义手势识别器,可识别长按,然后滑动。 我需要测量长按的长度是否超过1秒。如果是,则调用函数并等待滑动操作开始。
我的问题是,我现在知道媒体有多长时间的唯一方法是从touchesMoved中提取touchesBegan的时间戳。但是我想知道在调用touchesMoved之前经过的时间。
在调用touchesMoved之前,有没有办法知道水龙头的长度?
提前致谢!
答案 0 :(得分:2)
你可以使用may代码,它可以使用,但也许你应该处理一些细节
<。>在.h文件中你应该添加这些ivar: TestView *aView ;//the view which you press
NSThread *timerThread;
NSTimer *touchTimer;
NSDate *touchStartTime;
CGPoint touchStartPoint;
CGPoint lastTouchPoint;
<。>在.m文件中,您应该添加以下方法:
- (void)doSomething
{
NSLog(@"Long press!!!");
}
- (void)startTimerThead{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
touchTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self
selector:@selector(checkTouchTime:)
userInfo:nil repeats:YES];
[runLoop run];
[pool release];
}
- (void)stopTouchTimer{
if (touchTimer != nil) {
[touchTimer invalidate];
touchTimer = nil;
}
if (timerThread != nil) {
[timerThread cancel];
[timerThread release];
timerThread = nil;
}
}
#define DELETE_ACTIVING_TIME 1.0
- (void)checkTouchTime:(NSTimer*)timer{
NSDate *nowDate = [NSDate date];
NSTimeInterval didTouchTime = [nowDate timeIntervalSinceDate:touchStartTime];
if (didTouchTime > DELETE_ACTIVING_TIME){
[self stopTouchTimer];
[self doSomething];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
UIView *touchView = [touch view];
if ([touchView isKindOfClass:[TestView class]]) {
touchStartTime = [[NSDate date] retain];
if (nil == timerThread) {
timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThead) object:nil];
[timerThread start];
}
}
touchStartPoint = [touch locationInView:self.view];
lastTouchPoint = touchStartPoint;
}
#define TOUCH_MOVE_EFFECT_DIST 10.0f
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint movedPoint = [touch locationInView:self.view];
CGPoint deltaVector = CGPointMake(movedPoint.x - touchStartPoint.x, movedPoint.y - touchStartPoint.y);
if (fabsf(deltaVector.x) > TOUCH_MOVE_EFFECT_DIST
|| fabsf(deltaVector.y) > TOUCH_MOVE_EFFECT_DIST)
{
[self stopTouchTimer];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
UIView *touchView = [touch view];
CGPoint movedPoint = [touch locationInView:self.view];
CGPoint deltaVector = CGPointMake(movedPoint.x - touchStartPoint.x, movedPoint.y - touchStartPoint.y);
if ([touchView isKindOfClass:[TestView class]]) {
if (fabsf(deltaVector.x) < TOUCH_MOVE_EFFECT_DIST
&& fabsf(deltaVector.y) < TOUCH_MOVE_EFFECT_DIST) {
[self stopTouchTimer];
}
}
}