作者:朱克鋒
轉載請註明出處:http://blog.csdn.net/linux_zkf
水平和垂直的碰擦(Swipe)是簡單的手勢類型,您可以簡單地在自己的代碼中進行跟蹤,並通過它們執行某些動作。爲了檢測碰擦手勢,您需要跟蹤用戶手指在期望的座標軸方向上的運動。碰擦手勢如何形成是由您自己來決定的,也就是說,您需要確定用戶手指移動的距離是否足夠長,移動的軌跡是否足夠直,還有移動的速度是否足夠快。您可以保存初始的觸碰位置,並將它和後續的touch-moved事件報告的位置進行比較,進而做出這些判斷。
程序清單展示了一些基本的跟蹤方法,可以用於檢測某個視圖上發生的水平碰擦。在這個例子中,視圖將觸摸的初始位置存儲在名爲startTouchPosition的成員變量中。隨着用戶手指的移動,清單中的代碼將當前的觸摸位置和起始位置進行比較,確定是否爲碰擦手勢。如果觸摸在垂直方向上移動得太遠,就會被認爲不是碰擦手勢,並以不同的方式進行處理。但是,如果手指繼續在水平方向上移動,代碼就繼續將它作爲碰擦手勢來處理。一旦碰擦手勢在水平方向移動得足夠遠,以至於可以認爲是完整的手勢時,處理例程就會觸發相應的動作。檢測垂直方向上的碰擦手勢可以用類似的代碼,只是把x和y方向的計算互換一下就可以了。
程序清單 在視圖中跟蹤碰擦手勢
#define HORIZ_SWIPE_DRAG_MIN 12
#define VERT_SWIPE_DRAG_MAX 4
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
startTouchPosition = [touch locationInView:self];}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self];
// If the swipe tracks correctly.
if (fabsf(startTouchPosition.x - currentTouchPosition.x) >= HORIZ_SWIPE_DRAG_MIN &&
fabsf(startTouchPosition.y - currentTouchPosition.y) <= VERT_SWIPE_DRAG_MAX)
{
// It appears to be a swipe.
if (startTouchPosition.x < currentTouchPosition.x)
[self myProcessRightSwipe:touches withEvent:event];
else[self myProcessLeftSwipe:touches withEvent:event];
}
else
{
// Process a non-swipe event.
}
}