手勢是行動裝置直覺操作的基礎。iOS 自 3.2 起提供了一系列現成的手勢辨識器,而需要更客製的行為時,也可以自己繼承來實作。本文從基礎概念一路寫到自定義手勢的完整範例。
系統內建的六種常用手勢如下:
需要自定義時,繼承 UIGestureRecognizer 並匯入 <UIKit/UIGestureRecognizerSubclass.h>,一般需實作下列方法:
- (void)reset; - (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; // 以上方法宣告於 UIGestureRecognizer (UIGestureRecognizerProtected) 分類中
繼承關係如下:

六種手勢中,只有 UITapGestureRecognizer 屬於離散型手勢——一旦識別就無法取消,而且只會觸發一次回呼。
其餘五種都是連續型手勢:會在過程中多次觸發回呼,而且中途可以取消。從下圖可以清楚看到兩者呼叫次數的差異:

狀態列舉:
typedef NS_ENUM(NSInteger, UIGestureRecognizerState) {
UIGestureRecognizerStatePossible, // 尚未識別(可能已觸發觸摸事件),預設狀態
UIGestureRecognizerStateBegan, // 手勢已開始,已被識別但尚未完成
UIGestureRecognizerStateChanged, // 手勢狀態改變
UIGestureRecognizerStateEnded, // 手勢完成(手指已離開)
UIGestureRecognizerStateCancelled, // 手勢被取消,回到預設狀態
UIGestureRecognizerStateFailed, // 手勢識別失敗,回到預設狀態
UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
};
以旋轉手勢為例走一遍流程:兩根手指按在畫面上但不動,此時尚未識別(狀態 0),但觸摸開始事件其實已經觸發;一旦開始旋轉就會被識別並觸發回呼,狀態變為 1(Began),但這個狀態只存在一瞬間;接著進入狀態 2(Changed)並持續呼叫回呼;手指離開後狀態變為 3(Ended),最後再呼叫一次回呼。
對比之下,離散型的點按手勢要嘛被識別、要嘛失敗:假設設定為單擊一次,手指按下不放的期間什麼都不會發生,一放開立刻識別並觸發回呼,狀態直接為 3。
注意:一個手勢只能綁一個 View,但一個 View 可以掛多個手勢。另外強烈建議在真機測試——模擬器操作不夠靈敏,容易誤判為手勢失效(測試捏合與旋轉時,需按住 option 鍵再用觸控板或滑鼠操作)。
功能設計:兩張圖片各自綁上「拖動、捏合、旋轉、點按、長按」,根視圖則負責「輕掃」與自定義的「撓癢手勢」。

KMGestureRecognizer.h
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, Direction) {
DirectionUnknown,
DirectionLeft,
DirectionRight
};
@interface KMGestureRecognizer : UIGestureRecognizer
@property (assign, nonatomic) NSUInteger tickleCount; // 撓癢次數
@property (assign, nonatomic) CGPoint currentTickleStart; // 本次撓癢起始座標
@property (assign, nonatomic) Direction lastDirection; // 最後一次移動方向
@end
KMGestureRecognizer.m
#import "KMGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
@implementation KMGestureRecognizer
#define kMinTickleSpacing 20.0
#define kMaxTickleCount 3
- (void)reset
{
_tickleCount = 0;
_currentTickleStart = CGPointZero;
_lastDirection = DirectionUnknown;
// 若尚未進入識別流程,直接標記為失敗
if (self.state == UIGestureRecognizerStatePossible) {
self.state = UIGestureRecognizerStateFailed;
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
_currentTickleStart = [touch locationInView:self.view];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint tickleEnd = [touch locationInView:self.view];
// 比較 X 軸位移,判斷是向左還是向右
CGFloat tickleSpacing = tickleEnd.x - _currentTickleStart.x;
Direction currentDirection = tickleSpacing < 0 ? DirectionLeft : DirectionRight;
// 位移幅度需達門檻值
if (ABS(tickleSpacing) >= kMinTickleSpacing) {
// 必須是「來回」才算一次,連續同方向不計
if (_lastDirection == DirectionUnknown ||
(_lastDirection == DirectionLeft && currentDirection == DirectionRight) ||
(_lastDirection == DirectionRight && currentDirection == DirectionLeft)) {
_tickleCount++;
_currentTickleStart = tickleEnd;
_lastDirection = currentDirection;
// 累積達三次即完成識別
if (_tickleCount >= kMaxTickleCount &&
self.state == UIGestureRecognizerStatePossible) {
self.state = UIGestureRecognizerStateEnded;
}
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self reset];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self reset];
}
@end
ViewController.h
#import <UIKit/UIKit.h> #import "KMGestureRecognizer.h" @interface ViewController : UIViewController @property (strong, nonatomic) UIImageView *imgV; @property (strong, nonatomic) UIImageView *imgV2; @property (strong, nonatomic) KMGestureRecognizer *customGestureRecognizer; @end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
- (void)handlePan:(UIPanGestureRecognizer *)recognizer;
- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer;
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer;
- (void)handleTap:(UITapGestureRecognizer *)recognizer;
- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer;
- (void)handleSwipe:(UISwipeGestureRecognizer *)recognizer;
- (void)handleCustomGestureRecognizer:(KMGestureRecognizer *)recognizer;
- (void)bindPan:(UIImageView *)imgVCustom;
- (void)bindPinch:(UIImageView *)imgVCustom;
- (void)bindRotation:(UIImageView *)imgVCustom;
- (void)bindTap:(UIImageView *)imgVCustom;
- (void)bindLongPress:(UIImageView *)imgVCustom;
- (void)bindSwipe;
- (void)bingCustomGestureRecognizer;
- (void)layoutUI;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self layoutUI];
}
#pragma mark - 處理手勢
/**
* 拖動手勢
*/
- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
// 把當前視圖移到最上層
[recognizer.view.superview bringSubviewToFront:recognizer.view];
CGPoint center = recognizer.view.center;
CGFloat cornerRadius = recognizer.view.frame.size.width / 2;
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(center.x + translation.x,
center.y + translation.y);
// 位移量必須歸零,否則下一輪會重複累加
[recognizer setTranslation:CGPointZero inView:self.view];
if (recognizer.state == UIGestureRecognizerStateEnded) {
// 速度向量長度小於 200 時,滑行距離會很短
CGPoint velocity = [recognizer velocityInView:self.view];
CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
CGFloat slideMult = magnitude / 200;
// 依速度與比例推算終點
float slideFactor = 0.1 * slideMult;
CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),
center.y + (velocity.y * slideFactor));
// 限制在邊界內,避免被拖出畫面
finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),
self.view.bounds.size.width - cornerRadius);
finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),
self.view.bounds.size.height - cornerRadius);
[UIView animateWithDuration:slideFactor * 2
delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
recognizer.view.center = finalPoint;
} completion:nil];
}
}
/**
* 捏合手勢
*/
- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
CGFloat scale = recognizer.scale;
// 用 CGAffineTransformScale 是在「目前狀態」上累加縮放
recognizer.view.transform =
CGAffineTransformScale(recognizer.view.transform, scale, scale);
// 歸零,下次才能拿到正確的增量
recognizer.scale = 1.0;
}
/**
* 旋轉手勢
*/
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer
{
recognizer.view.transform =
CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
recognizer.rotation = 0.0;
}
/**
* 點按手勢:還原所有變形
*/
- (void)handleTap:(UITapGestureRecognizer *)recognizer
{
UIView *view = recognizer.view;
view.transform = CGAffineTransformMakeScale(1.0, 1.0);
view.transform = CGAffineTransformMakeRotation(0.0);
view.alpha = 1.0;
}
/**
* 長按手勢:降低透明度
*/
- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer
{
recognizer.view.alpha = 0.7;
}
/**
* 輕掃手勢
*/
- (void)handleSwipe:(UISwipeGestureRecognizer *)recognizer
{
// 以 block 封裝共用邏輯
void (^positionOperation)() = ^() {
CGPoint newPoint = recognizer.view.center;
newPoint.y -= 20.0;
_imgV.center = newPoint;
newPoint.y += 40.0;
_imgV2.center = newPoint;
};
switch (recognizer.direction) {
case UISwipeGestureRecognizerDirectionRight:
positionOperation();
break;
case UISwipeGestureRecognizerDirectionLeft:
positionOperation();
break;
case UISwipeGestureRecognizerDirectionUp:
break;
case UISwipeGestureRecognizerDirectionDown:
break;
}
}
/**
* 自定義撓癢手勢
*/
- (void)handleCustomGestureRecognizer:(KMGestureRecognizer *)recognizer
{
void (^positionOperation)() = ^() {
CGPoint newPoint = recognizer.view.center;
newPoint.x -= 20.0;
_imgV.center = newPoint;
newPoint.x += 40.0;
_imgV2.center = newPoint;
};
positionOperation();
}
#pragma mark - 綁定手勢
- (void)bindPan:(UIImageView *)imgVCustom
{
UIPanGestureRecognizer *recognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[imgVCustom addGestureRecognizer:recognizer];
}
- (void)bindPinch:(UIImageView *)imgVCustom
{
UIPinchGestureRecognizer *recognizer =
[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
[imgVCustom addGestureRecognizer:recognizer];
}
- (void)bindRotation:(UIImageView *)imgVCustom
{
UIRotationGestureRecognizer *recognizer =
[[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
[imgVCustom addGestureRecognizer:recognizer];
}
- (void)bindTap:(UIImageView *)imgVCustom
{
UITapGestureRecognizer *recognizer =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
recognizer.numberOfTapsRequired = 2; // 雙擊才觸發
recognizer.numberOfTouchesRequired = 1;
[imgVCustom addGestureRecognizer:recognizer];
}
- (void)bindLongPress:(UIImageView *)imgVCustom
{
UILongPressGestureRecognizer *recognizer =
[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
recognizer.minimumPressDuration = 0.5; // 預設即為 0.5 秒
[imgVCustom addGestureRecognizer:recognizer];
}
/**
* 綁定輕掃手勢
* 支援四個方向,但每個方向需各自建立一個手勢實例
*/
- (void)bindSwipe
{
// 向右輕掃
UISwipeGestureRecognizer *recognizer =
[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
recognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:recognizer];
[recognizer requireGestureRecognizerToFail:_customGestureRecognizer];
// 向左輕掃
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
recognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:recognizer];
[recognizer requireGestureRecognizerToFail:_customGestureRecognizer];
}
/**
* 綁定自定義撓癢手勢
*/
- (void)bingCustomGestureRecognizer
{
_customGestureRecognizer =
[[KMGestureRecognizer alloc] initWithTarget:self
action:@selector(handleCustomGestureRecognizer:)];
[self.view addGestureRecognizer:_customGestureRecognizer];
}
#pragma mark - 版面配置
- (void)layoutUI
{
// 第一張圖片
UIImage *img = [UIImage imageNamed:@"Emoticon_tusiji_icon"];
CGFloat cornerRadius = img.size.width;
_imgV = [[UIImageView alloc] initWithImage:img];
_imgV.frame = CGRectMake(20.0, 20.0, cornerRadius * 2, cornerRadius * 2);
_imgV.userInteractionEnabled = YES;
_imgV.layer.masksToBounds = YES;
_imgV.layer.cornerRadius = cornerRadius;
_imgV.layer.borderWidth = 2.0;
_imgV.layer.borderColor = [UIColor grayColor].CGColor;
[self.view addSubview:_imgV];
// 第二張圖片
img = [UIImage imageNamed:@"Emoticon_tusiji_icon2"];
cornerRadius = img.size.width;
_imgV2 = [[UIImageView alloc] initWithImage:img];
_imgV2.frame = CGRectMake(20.0, 40.0 + _imgV.frame.size.height,
cornerRadius * 2, cornerRadius * 2);
_imgV2.userInteractionEnabled = YES;
_imgV2.layer.masksToBounds = YES;
_imgV2.layer.cornerRadius = cornerRadius;
_imgV2.layer.borderWidth = 2.0;
_imgV2.layer.borderColor = [UIColor orangeColor].CGColor;
[self.view addSubview:_imgV2];
// 為兩張圖片綁定手勢
[self bindPan:_imgV];
[self bindPinch:_imgV];
[self bindRotation:_imgV];
[self bindTap:_imgV];
[self bindLongPress:_imgV];
[self bindPan:_imgV2];
[self bindPinch:_imgV2];
[self bindRotation:_imgV2];
[self bindTap:_imgV2];
[self bindLongPress:_imgV2];
// 先綁自定義手勢,才能處理與輕掃的優先順序
[self bingCustomGestureRecognizer];
[self bindSwipe];
}
@end
位移量要歸零。handlePan: 中呼叫 setTranslation:CGPointZero inView:、捏合後重設 scale = 1.0、旋轉後重設 rotation = 0.0——這些都是必要的。手勢辨識器回報的是「自上次以來的增量」,不歸零就會不断累加,圖片會飛出畫面。
用 requireGestureRecognizerToFail: 處理衝突。範例中讓左右輕掃必須「等撓癢手勢失敗後」才生效,這正是自定義手勢最實用的地方:系統內建手勢無法表達「左右來回三次」這種複合行為,但只要透過失敗依賴關係,就能讓自定義手勢優先攔截,其餘情況自動退回輕掃。