在ios开发中,有系统内置的手势,同时我们也可以创建自己的手势。estureRecognizer将低级别的转换为高级别的执行行为,是你绑定到view的对象,当发生手势,绑定到的view对象会响应,它确定这个动作是否对应一个特定的手势(swipe,pinch,pan,rotation).如果它能识别这个手势,那么就会向绑定它的view发送消息。
UIKit框架提供了一些预定义的GestureRecognizer.包含下列手势
- UITapGestureRecognizer敲击手势(单击和双击)
- UIPanGestureRecognizer(拖动手势)
- UIPinchGestureRecognizer(缩放手势)
- UISwipeGestureRecognizer(擦碰手势)
- UIRotationGestureRecognizer(旋转手势)
- UILongPressGestureRecognizer(长按手势)
1、UIGestureRecognizerStatePossible (识别器还没识别手势,但是可能评估触摸事件,为默认状态)
2、UIGestureRecognizerStateBegan (识别器已经识别出手势,runloop将调用其对应的响应事件)
3、UIGestureRecognizerStateChanged (识别器已经识别出手势,runloop将调用其对应的响应事件)
4、UIGestureRecognizerStateEnded (识别器已经识别出手势将要结束,响应事件将要发生,手势的状态将要改为默认状态)
5、UIGestureRecognizerStateCancelled (识别器识别手势被取消,手势将要恢复默认状态)
6、UIGestureRecognizerStateFailed (识别器无法识别手势,不会调用响应手势,手势状态将要恢复为默认状态)
UIGestureRecognizer继承于NSObject
1、初始化方法
- (instancetype)initWithTarget:(id)target action:(SEL)action; // designated initializer
2、手势对应事件的添加与移除
- (void)addTarget:(id)target action:(SEL)action;
- (void)removeTarget:(id)target action:(SEL)action;
3、属性
@property(nonatomic,readonly) UIGestureRecognizerState state; (通过此属性我们可以获取手势的实时状态)
@property(nonatomic,assign) id <UIGestureRecognizerDelegate> delegate; (通过设置其代理,可以调用其代理方法)
@property(nonatomic, getter=isEnabled) BOOL enabled (若为no则无法识别手势,默认为yes)
@property(nonatomic,readonly) UIView *view (手势所依附的view)
@property(nonatomic) BOOL cancelsTouchesInView
4、方法
- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer; (该手势响应时其他手 势为无效)
- (CGPoint)locationInView:(UIView*)view; (获取手势触摸点)
- (NSUInteger)numberOfTouches; (获取手势点击次数)
- (CGPoint)locationOfTouch:(NSUInteger)touchIndex inView:(UIView*)view (获取一个特定的触摸事件所触摸的位置)
5、代理方法
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer (此方法在gesture recognizer视图转出UIGestureRecognizerStatePossible状态时调用,如果返回NO,则转换到UIGestureRecognizerStateFailed;如果返回YES,则继续识别触摸序列.(默认情况下为YES)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer; (如果返回YES,则两个gesture recognizers可同时识别,如果返回NO,则并不保证两个gesture recognizers必不能同时识别,因为另外一个gesture recognizer的此方法可能返回YES。也就是说两个gesture recognizers的delegate方法只要任意一个返回YES,则这两个就可以同时识别;只有两个都返回NO的时候,才是互斥的。默认情况下是返回NO)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognize
r:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0);
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizershouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0);
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch; (此方法在window对象在有触摸事件发生时,调用gesture recognizer的touchesBegan:withEvent:方法之前调用,如果返回 NO,则gesture recognizer不会看到此触摸事件)