iOS手势
在iPhone中,我们除了用touchesBegan、touchesMoved、touchesEnded、touchesCancelled这组方法来控制使用者的手指触控外,也可以用UIGestureRecognizer 的衍生类别来进行判断,该类别的好处是有自己现成的手势,开发者可以自己计算手指移动的轨迹。
1、首先看下touchesBegan、touchesMoved、touchesEnded、touchesCancelled者四个方法的使用。
touchesBegan:是用户第一次接触屏幕时响应的方法。
- (void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *)event{
NSUInteger numType = [[touches anyObject] tapCount];
NSUInteger numTouches = [touches count];
}
touchesMoved:是用户手指移过屏幕时响应的方法。这里可以得到当前手指的位置以及原来的位置等信息。
touchesEnded:用户手指离开屏幕时响应的方法。
touchesCancelled:当发生某些事件导致手势中断时响应的方法,要说明的是调用了该方法就不会响应touchesEned方法了。
2、现在了解下UIGestureRecognizer的使用
UIGestureRecognizer衍生类别有:UITapGestureRecognizer、UIPinchGestureRecognizer、UIRotationGestureRecognizer、UISwipeGestureRecognizer、UIPanGEstureRecognizer、UiLongPressGestureRecognizer,他们所代表的手势分别是Tap(点一下)、Pinch(二指往外或往内拨动)、Rotation(旋转)、Swipe(滑动、快速移动)、Pan(拖移、慢速移动)、LongPress(长时间按)。
- (void)viewDidLoad {
UISwipeGestureRecognizer* recognizer;
// handleSwipeFrom 是偵測到手势,所要响应的方法
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSwipeFrom)];
// 不同的 Recognizer 有不同的实体变数
// 例如 SwipeGesture 可以指定方向
// 而 TapGesture 則可以指定次數
recognizer.direction = UISwipeGestureRecognizerDirectionUp
[self.view addGestureRecognizer:recognizer];
[recognizer release];
}
- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
// 触发手勢事件后,在这里作些事情
// 底下是刪除手势的方法
[self.view removeGestureRecognizer:recognizer];
}
但是这里有个问题,Tap和LongPress,一个是点击一次一个长按,所以当我们点击屏幕的时候,我们怎么分清这是点击还是准备长按呢?Swipe和Pan也有这样的问题,只要手指一移动就会出发Pan,这样的话永远不会出发Swipe,这个问题要出现的前提是同时注册了这些手势。
所以需要一个解决方法:幸好UIGestureRecognizer类提供了一个方法requireGestureRecognizerToFail它可以指定某一个recognizer,即便自己满足条件; 也不会立即执行会等到指定的recognizer确定失败之后才触发。
- (void)viewDidLoad {
// 单击的 Recognizer
UITapGestureRecognizer* singleRecognizer;
singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSingleTapFrom)];
singleTapRecognizer.numberOfTapsRequired = 1;
// 单击
[self.view addGestureRecognizer:singleRecognizer];
// 双击的 Recognizer
UITapGestureRecognizer* doubleRecognizer;
doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleDoubleTapFrom)];
doubleTapRecognizer.numberOfTapsRequired = 2;
// 双击
[self.view addGestureRecognizer:doubleRecognizer];
// 关键在这一行,如果双击确定偵測失败才會触发单击
[singleRecognizer requireGestureRecognizerToFail:doubleRecognizer];
[singleRecognizer release];
[doubleRecognizer release];
}