How can I tell a UIGestureRecognizer to cancel an existing touch?

前端 未结 7 1046
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 03:36

I have a UIPanGestureRecognizer I am using to track an object (UIImageView) below a user\'s finger. I only care about motion on the X axis, and if

相关标签:
7条回答
  • 2020-12-13 03:49

    This little trick works for me.

    @implementation UIGestureRecognizer (Cancel)
    
    - (void)cancel {
        self.enabled = NO;
        self.enabled = YES;
    }
    
    @end
    

    From the UIGestureRecognizer @enabled documentation:

    Disables a gesture recognizers so it does not receive touches. The default value is YES. If you change this property to NO while a gesture recognizer is currently recognizing a gesture, the gesture recognizer transitions to a cancelled state.

    0 讨论(0)
  • 2020-12-13 03:53

    According to the documentation you can subclass you gesture recogniser:

    In YourPanGestureRecognizer.m:

    #import "YourPanGestureRecognizer.h"
    
    @implementation YourPanGestureRecognizer
    
    - (void) cancelGesture {
        self.state=UIGestureRecognizerStateCancelled;
    }
    
    @end
    

    In YourPanGestureRecognizer.h:

    #import <UIKit/UIKit.h>
    #import <UIKit/UIGestureRecognizerSubclass.h>
    
    @interface NPPanGestureRecognizer: UIPanGestureRecognizer
    
    - (void) cancelGesture;
    
    @end
    

    Now you can call if from anywhere

    YourPanGestureRecognizer *panRecognizer = [[YourPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMoved:)];
    [self.view addGestureRecognizer:panRecognizer];
    [...]
    -(void) panMoved:(YourPanGestureRecognizer*)sender {
        [sender cancelGesture]; // This will be called twice
    }
    

    Ref: https://developer.apple.com/documentation/uikit/uigesturerecognizer?language=objc

    0 讨论(0)
  • 2020-12-13 03:55

    Obj-C:

    recognizer.enabled = NO;
    recognizer.enabled = YES;
    

    Swift 3:

    recognizer.isEnabled = false
    recognizer.isEnabled = true
    
    0 讨论(0)
  • 2020-12-13 04:01

    @matej's answer in Swift.

    extension UIGestureRecognizer {
      func cancel() {
        isEnabled = false
        isEnabled = true
      }
    }
    
    0 讨论(0)
  • 2020-12-13 04:05

    How about this from the apple docs:

    @property(nonatomic, getter=isEnabled) BOOL enabled
    

    Disables a gesture recognizers so it does not receive touches. The default value is YES. If you change this property to NO while a gesture recognizer is currently recognizing a gesture, the gesture recognizer transitions to a cancelled state.

    0 讨论(0)
  • 2020-12-13 04:07

    Just set recognizer.state in your handlePan(_ recognizer: UIPanGestureRecognizer) method to .ended or .cancelled

    0 讨论(0)
提交回复
热议问题