iOS 裝置支援多點觸摸,也就是說螢幕上可以同時有多支手指按下、拖動、抬起。系統會把觸摸事件交給目前視圖處理;若該視圖不處理,事件就沿著響應者鏈往上一層傳遞。處理觸摸的方法共有四個,都定義在 UIResponder 上。
先建立一個繼承 UIView 的自訂視圖,並在視圖控制器中把它載入:
- (void)viewDidLoad {
[super viewDidLoad];
// 建立負責響應觸摸的視圖
LinView *pView = [[LinView alloc] initWithFrame:CGRectMake(0, 0, 320, 450)];
pView.backgroundColor = [UIColor blueColor]; // 與根視圖區分
[self.view addSubview:pView];
[pView release];
}
在自訂視圖的標頭檔加入一個用來記錄兩點距離的成員:
@interface LinView : UIView {
float _lastDistance; // 存放兩點之間距離變化的資訊
}
@end
@implementation LinView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.multipleTouchEnabled = YES; // 開啟多點觸摸
self.userInteractionEnabled = YES;
}
return self;
}
#pragma mark ----- 觸摸開始 -----
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *pTouch = [touches anyObject]; // 取任一個 touch
CGPoint point = [pTouch locationInView:self]; // 取得座標
NSLog(@"觸摸點的座標:%@", NSStringFromCGPoint(point));
NSUInteger tapCount = [pTouch tapCount];
if (tapCount == 1) {
// 0.2 秒內只觸摸一次視為單擊
[self performSelector:@selector(singleTouch:) withObject:nil afterDelay:0.2];
} else if (tapCount == 2) {
// 取消待處理的單擊,否則雙擊會被當成「單擊 + 雙擊」
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(singleTouch:)
object:nil];
[self doubleTouch:nil];
}
}
- (void)singleTouch:(id)sender {
NSLog(@"此時是單擊的操作");
}
- (void)doubleTouch:(id)sender {
NSLog(@"此時是雙擊的操作");
}
#pragma mark ----- 觸摸移動(滑動) -----
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *array = [touches allObjects];
UITouch *pTouch1 = [array objectAtIndex:0];
UITouch *pTouch2 = [array objectAtIndex:1];
CGPoint point1 = [pTouch1 locationInView:self];
CGPoint point2 = [pTouch2 locationInView:self];
double distance = [self distanceOfPoint:point1 withPoint:point2];
if ((distance - _lastDistance) > 0) {
// 距離變大,通常對應放大(捏合張開)
NSLog(@"兩點距離變大");
} else {
// 距離變小,通常對應縮小(捏合收攏)
NSLog(@"兩點距離變小");
}
_lastDistance = distance; // 更新基準值
}
// 封裝兩點距離的計算
- (double)distanceOfPoint:(CGPoint)point1 withPoint:(CGPoint)point2 {
double num1 = pow(point1.x - point2.x, 2);
double num2 = pow(point1.y - point2.y, 2);
return sqrt(num1 + num2);
}
#pragma mark ----- 觸摸結束 -----
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// 手指離開螢幕時觸發
}
#pragma mark ----- 觸摸被中斷 -----
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
// 例如來電導致取消,通常不實作
}
@end
這段程式碼示範了兩個實用技巧。第一,單雙擊的判定並非靠系統 API,而是「延遲 0.2 秒執行單擊,若在期限內收到第二次觸摸就取消排程」——performSelector:withObject:afterDelay: 搭配 cancelPreviousPerformRequestsWithTarget:selector:object: 是標準組合。第二,判斷捏合方向不必記錄每個手指的位移,只要比較「兩點間距離」的變化即可,這也是多點觸摸手勢最常見的推導方式。
另外要留意,touchesMoved: 中直接取 objectAtIndex:1 在只有單指拖動時會越界,實務上應先檢查 touches.count。