處理螢幕滑動有兩種常見思路:一是用系統的 UISwipeGestureRecognizer,二是直接攔截更底層的觸控事件。前者簡單直覺,後者彈性大但複雜得多。
先建立一個用來接收手勢的視圖,再依方向掛上手勢識別器。上下左右各自需要一個獨立的 recognizer 實例。
// 建立可接收觸動的範圍 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:(UISwipeGestureRecognizerDirectionLeft)]; [infoView addGestureRecognizer:recognizer]; // 上下方向同理,取消註解即可啟用 // recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)]; // [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)]; // [self.view 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(@"向上滑");
}
}
要注意的是手勢只能掛在 view 的範圍內,超出 infoView 邊界的觸摸不會被偵測。若希望整個畫面都能響應,把 recognizer 加到 self.view 上即可。
另一種思路是自己組出 GSEvent 並送進系統事件佇列,模擬一次按鍵/觸控事件:
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、GSGetPurpleApplicationPort 等私有介面,且結構体位域配置與 iOS 版本高度相關,僅適用於越獄環境或研究用途,不建議出現在正式產品中。一般開發情境下,用 UIGestureRecognizer 系列已經能涵蓋絕大多數需求;若需要更細緻的追蹤(例如跟手拖曳、多點觸控判定),則該改為實作 UIResponder 的 touchesBegan/touchesMoved/touchesEnded 四個方法。