下面是我該怎麼做的:創建一個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