下面是我该怎么做的:创建一个UISwipeGestureRecognizer
的子类。这个子类的目的只是为了记住它在touchesBegan:withEvent:
方法中收到的第一个也是最后一个UITouch
对象。其他一切都会被转发到super
。
当识别器触发其操作时,识别器将作为参数sender
传入。您可以询问初始触摸对象和最终触摸对象,然后使用locationInView:
方法和timestamp
属性计算滑动速度(速度=距离变化/时间变化)。
所以它会是这样的:
@interface DDSwipeGestureRecognizer : UISwipeGestureRecognizer
@property (nonatomic, retain) UITouch * firstTouch;
@property (nonatomic, retain) UITouch * lastTouch;
@end
@implementation DDSwipeGestureRecognizer
@synthesize firstTouch, lastTouch;
- (void) dealloc {
[firstTouch release];
[lastTouch release];
[super dealloc];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self setFirstTouch:[touches anyObject]];
[super touchesBegan:touches withEvent:event];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self setLastTouch:[touches anyObject]];
[super touchesEnded:touches withEvent:event];
}
@end
然后在其他地方,你会怎么做:
DDSwipeGestureRecognizer *swipe = [[DDSwipeGestureRecognizer alloc] init];
[swipe setTarget:self];
[swipe setAction:@selector(swiped:)];
[myView addGestureRecognizer:swipe];
[swipe release];
和你的行动将是这样的:
- (void) swiped:(DDSwipeGestureRecognizer *)recognizer {
CGPoint firstPoint = [[recognizer firstTouch] locationInView:myView];
CGPoint lastPoint = [[recognizer lastTouch] locationInView:myView];
CGFloat distance = ...; // the distance between firstPoint and lastPoint
NSTimeInterval elapsedTime = [[recognizer lastTouch] timestamp] - [[recognizer firstTouch] timestamp];
CGFloat velocity = distance/elapsedTime;
NSLog(@"the velocity of the swipe was %f points per second", velocity);
}
警告:在浏览器中键入的代码,未编译。警告执行者。
我在这里,并试图整合每个人的意见和答案,我非常感谢。至于你之前的评论,我也试着回复一下,所以我可以投票并回馈给那些帮助过的人。 – Mytheral 2011-02-02 12:44:29