手勢(Gesture)指的是從「一或多支手指接觸螢幕」開始,直到「所有手指離開螢幕」為止所發生的一整串事件。UIGestureRecognizer 是一個物件,它知道如何觀察使用者產生的事件流,並判斷何時符合預定義的手勢型態,於是開發者不必再手算位移與角度。
小技巧:在模擬器中按住 option 鍵拖動,可以模擬雙指手勢。
@interface LinViewController : UIViewController
@property (retain, nonatomic) UIView *mView;
@end
@implementation LinViewController
- (void)viewDidLoad {
[super viewDidLoad];
// ----- 點擊手勢 -----
UITapGestureRecognizer *pSingleTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(singleGesture:)];
[self.view addGestureRecognizer:pSingleTap];
UITapGestureRecognizer *pDoubleTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(doubleGesture:)];
pDoubleTap.numberOfTapsRequired = 2; // 預設為 1
[self.view addGestureRecognizer:pDoubleTap];
// 雙擊存在時,讓單擊不要觸發
[pSingleTap requireGestureRecognizerToFail:pDoubleTap];
[pDoubleTap release];
[pSingleTap release];
// ----- 滑動手勢 -----
UISwipeGestureRecognizer *pSwip = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(swipGesture:)];
pSwip.direction = UISwipeGestureRecognizerDirectionRight; // 共四個方向
[self.view addGestureRecognizer:pSwip];
[pSwip release];
// ----- 拖動手勢 -----
UIPanGestureRecognizer *pPan = [[UIPanGestureRecognizer alloc]
initWithTarget:self action:@selector(panGesture:)];
[self.view addGestureRecognizer:pPan];
[pPan release];
// ----- 長按手勢 -----
UILongPressGestureRecognizer *pLongPress = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(longPressGesture:)];
pLongPress.minimumPressDuration = 2; // 兩秒以上才判定為長按
[self.view addGestureRecognizer:pLongPress];
[pLongPress release];
// ----- 旋轉手勢 -----
UIRotationGestureRecognizer *pRotation = [[UIRotationGestureRecognizer alloc]
initWithTarget:self action:@selector(rotationGesture:)];
[self.view addGestureRecognizer:pRotation];
[pRotation release];
}
#pragma mark ----- 各手勢對應的方法 -----
- (void)singleGesture:(UITapGestureRecognizer *)tap {
NSLog(@"單擊操作");
}
- (void)doubleGesture:(UITapGestureRecognizer *)tap {
NSLog(@"雙擊操作");
}
- (void)swipGesture:(UISwipeGestureRecognizer *)swip {
NSLog(@"滑動操作,此處為向右滑動");
}
- (void)panGesture:(UIPanGestureRecognizer *)pan {
// 取得平移手勢在視圖上的座標,把視圖中心移到該點
CGPoint point = [pan locationInView:self.view];
self.mView.center = point;
NSLog(@"%@", NSStringFromCGPoint(point));
}
- (void)longPressGesture:(UILongPressGestureRecognizer *)longPress {
NSLog(@"長按操作");
}
- (void)rotationGesture:(UIRotationGestureRecognizer *)rotation {
// 把弧度換成角度,讓視圖做出對應反應
float degree = rotation.rotation * (180 / M_PI);
NSLog(@"旋轉的角度為 %.2f", degree);
}
- (void)dealloc {
[_mView release];
[super dealloc];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
三個實務重點。第一,手势之間存在互斥原則:一旦辨識出某手勢,後續同類手勢便不再被辨識,因此單擊與雙擊並存時必須用 requireGestureRecognizerToFail: 明確排出優先順序。第二,UIRotationGestureRecognizer 的 rotation 是弧度而非角度,顯示或套用動畫前記得換算。第三,手勢必須 addGestureRecognizer 到「真正要接收事件的視圖」上,掛在 self.view 還是掛在自訂子視圖,會直接決定命中範圍。