iOS Programming – 觸摸事件處理(2)
在上一篇《iOS Programming – 觸摸事件處理(1)》中瞭解觸摸、事件和響應者之後,接下去學習如何處理用戶的觸摸事件。首先觸摸的對象是視圖,而視圖的類UIView繼承了UIRespnder類,但是要對事件作出處理,還需要重寫UIResponder類中定義的事件處理函數。根據不通的觸摸狀態,程序會調用相應的處理函數,這些函數包括以下幾個:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
當手指接觸屏幕時,就會調用touchesBegan:withEvent方法;
當手指在屏幕上移時,動就會調用touchesMoved:withEvent方法;
當手指離開屏幕時,就會調用touchesEnded:withEvent方法;
當觸摸被取消(比如觸摸過程中被來電打斷),就會調用touchesCancelled:withEvent方法。而這幾個方法被調用時,正好對應了UITouch類中phase屬性的4個枚舉值。
上面的四個事件方法,在開發過程中並不要求全部實現,可以根據需要重寫特定的方法。對於這4個方法,都有兩個相同的參數:NSSet類型的touches和UIEvent類型的event。其中touches表示觸摸產生的所有UITouch對象,而event表示特定的事件。因爲UIEvent包含了整個觸摸過程中所有的觸摸對象,因此可以調用allTouches方法獲取該事件內所有的觸摸對象,也可以調用touchesForVIew:或者touchesForWindows:取出特定視圖或者窗口上的觸摸對象。在這幾個事件中,都可以拿到觸摸對象,然後根據其位置,狀態,時間屬性做邏輯處理。
例如:
{
UITouch * touch = [touches anyObject];
if (touch.tapCount == 2 )
{
self.view.backgroundColor = [UIColor redColor];
}
}
上面的例子說明在觸摸手指離開後,根據tapCount點擊的次數來設置當前視圖的背景色。不管時一個手指還是多個手指,輕擊操作都會使每個觸摸對象的tapCount加1,由於上面的例子不需要知道具體觸摸對象的位置或時間等,因此可以直接調用touches的anyObject方法來獲取任意一個觸摸對象然後判斷其tapCount的值即可。
檢測tapCount可以放在touchesBegan也可以touchesEnded,不過一般後者跟準確,因爲touchesEnded可以保證所有的手指都已經離開屏幕,這樣就不會把輕擊動作和按下拖動等動作混淆。
輕擊操作很容易引起歧義,比如當用戶點了一次之後,並不知道用戶是想單擊還是隻是雙擊的一部分,或者點了兩次之後並不知道用戶是想雙擊還是繼續點擊。爲了解決這個問題,一般可以使用“延遲調用”函數。
例如:
{
UITouch * touch = [touches anyObject];
if (touch.tapCount == 1 )
{
[self performSelector:@selector(setBackground:) withObject:[UIColor blueColor] afterDelay: 2 ];
self.view.backgroundColor = [UIColor redColor];
}
}
上面代碼表示在第一次輕擊之後,沒有直接更改視圖的背景屬性,而是通過performSelector:withObject:afterDelay:方法設置2秒中後更改。
{
UITouch * touch = [touches anyObject];
if (touch.tapCount == 2 )
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setBackground:) object :[UIColor redColor]];
self.view.backgroundColor = [UIColor redColor];
}
}
雙擊就是兩次單擊的組合,因此在第一次點擊的時候,設置背景色的方法已經啓動,在檢測到雙擊的時候先要把先前對應的方法取消掉,可以通過調用NSObject類的cancelPreviousPerformRequestWithTarget:selector:object方法取消指定對象的方法調用,然後調用雙擊對應的方法設置背景色爲紅色。
下面舉個例子創建可以拖動的視圖,這個主要通過觸摸對象的位置座標來實現。因此調用觸摸對象的locationInView:方法即可。
例如:
- ( void )touchesBegan:(NSSet * )touches withEvent:(UIEvent * ) event
{
UITouch * touch = [touches anyObject];
originalLocation = [touch locationInView:self.view];
}
- ( void )touchesMoved:(NSSet * )touches withEvent:(UIEvent * ) event
{
UITouch * touch = [touches anyObject];
CGPoint currentLocation = [touch locationInView:self.view];
CGRect frame = self.view.frame;
frame.origin.x += currentLocation.x - originalLocation.x;
frame.origin.y += currentLocation.y - originalLocation.y;
self.view.frame = frame;
}
這裏先在touchesBegan中通過[touch locationInView:self.view]獲取手指觸摸在當前視圖上的位置,用CGPoint變量記錄,然後在手指移動事件touchesMoved方法中獲取觸摸對象當前位置,並通過於與原始位置的差值計算出移動偏移量,再設置當前視圖的位置。