要攔截使用者的觸控行為,最正規的方式是使用手勢辨識器。以下示範如何限定一個區域,並在其中判斷四個方向的滑動。
先建立一個用來接收觸控的 view(注意它的 frame 就是感應範圍,超出就收不到事件),再掛上輕掃手勢:
// 在初始化方法中建立感應範圍
infoView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 220, 280)];
infoView.backgroundColor = [UIColor blueColor];
infoView.alpha = 0.6;
[self.view addSubview:infoView];
/****************** 手勢辨識 ******************/
// 支援上下左右四個方向,此處只啟用左右
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[infoView addGestureRecognizer:recognizer];
// 需要向上輕掃時取消註解即可
// recognizer = [[UISwipeGestureRecognizer alloc]
// initWithTarget:self action:@selector(handleSwipeFrom:)];
// [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];
// [self.view addGestureRecognizer:recognizer];
// recognizer = [[UISwipeGestureRecognizer alloc]
// initWithTarget:self action:@selector(handleSwipeFrom:)];
// [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
// [self.view addGestureRecognizer:recognizer];
recognizer = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[infoView addGestureRecognizer:recognizer];
回呼方法中依方向分別處理:
- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer
{
if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
NSLog(@"向左滑");
}
if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
NSLog(@"向右滑");
}
if (recognizer.direction == UISwipeGestureRecognizerDirectionDown) {
NSLog(@"向下滑");
}
if (recognizer.direction == UISwipeGestureRecognizerDirectionUp) {
NSLog(@"向上滑");
}
}
以下程式碼展示了如何直接構造底層事件並送出,這是早期越獄社群流傳的做法:
GSEventRecord header;
GSHardwareKeyInfo key = {0, 0, 0, 0, 1, {'a'}, 1, {'a'}, 0, 0, 0, 0};
memset(&header, 0, sizeof(header));
header.type = kGSEventKeyDown;
header.infoSize = sizeof(GSHardwareKeyInfo);
header.timestamp = mach_absolute_time();
struct
{
GSEventRecord header1;
GSHardwareKeyInfo key1;
} event = {header, key};
GSSendEvent(&event, GSGetPurpleApplicationPort());
GSEvent、GSSendEvent、GSGetPurpleApplicationPort 全都是未公開的私有 API。使用它們會有幾個實際後果:一是 App Store 審核會直接以「使用私有 API」為由退回;二是這些介面沒有相容性承諾,iOS 版本一升就可能編譯失敗或執行時崩潰;三是它模擬的是實體按鍵事件,用途與處理觸控手勢完全不同,不能互相取代。
結論很清楚:處理觸控就用 UIGestureRecognizer 家族;若真的需要更底層的觸控追蹤,正確的做法是繼承 UIView 並覆寫 touchesBegan:withEvent:、touchesMoved:withEvent:、touchesEnded:withEvent: 這組方法,這些都是公開 API,能取得每根手指的座標變化,足以實作任何自定義手勢。