gpt4 book ai didi

iOS自定义手势识别器测量长按的长度

转载 作者:行者123 更新时间:2023-11-28 22:52:14 29 4
gpt4 key购买 nike

在我的应用程序中,我想创建一个自定义手势识别器来识别长按和滑动。我需要测量长按的时间是否超过1秒。如果是,则调用一个函数并等待滑动 Action 开始。

我的问题是,我现在唯一知道按下时间的方法是从 touchesMoved 中提取 touchesBegan 的时间戳。但是我想知道调用 touchesMoved 之前耗时。

有没有办法在调用 touchesMoved 之前知道点击的长度?

提前致谢!

最佳答案

你可以用可能的代码,它可以用,但也许你应该处理一些细节

在 .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];
}
}


}

关于iOS自定义手势识别器测量长按的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11669212/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com