UIEvent 代表一個事件,它是由硬體捕捉到的、用來表示使用者操作裝置的物件,共分為三類:觸摸事件、晃動事件與遠程控制事件。
觸摸事件是使用者透過手指觸碰螢幕來操作物件或輸入資料,支援多點觸摸,一次可以包含一個到多個觸碰點。
UIView 因為繼承自 UIResponder,所以本身支援觸摸事件,也支援多點觸摸。要自訂觸摸行為,做法是建立 UIView 的子類別並實作以下方法:
touchesBegan:withEvent:touchesMoved:withEvent:touchesEnded:withEvent:touchesCancelled:withEvent:手勢則可以理解為「有規律的觸摸」。UITouch 代表螢幕上的一根手指,可以取得觸摸的位置與時間;而 touches 集合中包含了該視圖上的所有觸碰資訊。
響應者鏈顧名思義,是由多個響應者物件串起來的一條鏈。UIResponder 是響應者的抽象父類別,iOS 中所有能回應事件(觸摸、晃動、遠程)的物件都是響應者,其子類別自然也具備這個能力。
硬體偵測到觸摸後,會把資訊交給 UIApplication,開始往下尋找合適的響應者:
UIApplication → window → viewController → view → 所有子視圖
最終確認觸摸位置,完成響應者鏈的查詢。
找到響應者後,只要在該類別中實作 touchesBegan:withEvent: 等方法,就能處理這個事件。如果響應者沒有實作,事件會繼續往下傳遞;若一路都沒有響應者處理,這次觸摸就會被丟棄。
事件處理的順序與查詢時相反:
子視圖 → view → viewController → window → UIApplication
響應者鏈是可以被中斷的。視圖有個 userInteractionEnabled 屬性,設為 NO 之後就能阻斷查詢過程。
以下做一個簡單的互動:按下時隨機變色,拖曳時跟著移動,放開時印出訊息。
#import "TestView.h"
#define KRandomColor (arc4random() % 256 / 255.0)
@interface TestView () {
CGPoint _start; // 觸摸開始的位置
}
@end
@implementation TestView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor redColor];
}
return self;
}
// 一次觸摸事件只會呼叫一次
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.backgroundColor = [UIColor colorWithRed:KRandomColor
green:KRandomColor
blue:KRandomColor
alpha:1];
_start = [[touches anyObject] locationInView:self];
NSLog(@"點我改變顏色");
}
// 手指尚未離開前會持續呼叫
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint nowPoint = [[touches anyObject] locationInView:self];
CGFloat x = nowPoint.x - _start.x;
CGFloat y = nowPoint.y - _start.y;
self.center = CGPointMake(self.center.x + x, self.center.y + y);
NSLog(@"%@", NSStringFromCGPoint(nowPoint));
}
// 觸摸結束
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"結束了");
}
// 觸摸被其他事件打斷,例如來電
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}
@end
這裡有個實作上的細節值得注意:touchesMoved: 中每次都拿「目前位置減起始位置」的位移量去疊加中心點,若採用累加式位移會造成過衝,改用差值法比較穩定;若要更精確,可在 touchesBegan: 記錄初始 center,之後都用「初始 center 加位移」計算。