IOS defines the detailed explanation of gesture listener, and uigesturerecognizer is used to respond to gesture events such as kneading, rotation, translation, clicking and long pressing

Time:2022-6-20

In IOS, we can monitor touch events through uitouch, but it is very troublesome for uitouch to monitor gesture events such as kneading, rotation and long press. Available in IOSUIGestureRecognizerSubclasses of help us realize kneading, rotation and other special gesture monitoring concisely. And a view can add multiple different gesture listeners.

Enable userinteractionenabled

By default, uiview in IOS cannot respond to events. We need to enable ituserInteractionEnabledEvent response can only be carried out. In the following code, we create a picture view and start the event response. Uiview passedaddGestureRecognizerAdd gesture listeners andremoveGestureRecognizer Delete gesture listener

//Create picture view
- (void) creareImg {
    UIImage* image = [UIImage imageNamed:@"zz.jpeg"];
    _imageView = [[UIImageView alloc] initWithImage:image];
    UIScreen* screen = [UIScreen mainScreen];
    const int width = 200;
    const int height = 100;
    const float x = screen.bounds.size.width / 2 - width / 2;
    const float y = screen.bounds.size.height / 2 - height;
    _imageView.frame = CGRectMake(x, y, width, height);
    _imageView.userInteractionEnabled = YES;
    [self.view addSubview:_imageView];
}

Learn about uigestruerecognizer

Before we start using custom gestures, let’s take a lookUIGestrueRecognizerBecause customization is based onUIGestrueRecognizerInherited implementation.UIGestrueRecognizerIs a gesture listener, which can set multiple fingers to trigger triggering events at the same time. It has a proxy agreementUIGestureRecognizerDelegateLet me take a look at its main properties, APIs and proxy methods.

attribute
name type explain Default
state UIGestureRecognizerState The current gesture status can be divided into gesture start, gesture change, gesture end, etc
enabled BOOL Enable or not YES
view UIView View of gesture monitoring
requiresExclusiveTouchType BOOL Whether to ignore other gesture types. Setting yes will only respond to one gesture type NO
numberOfTouches NSUInteger How many fingers trigger the gesture 1
API
  • - (instancetype)initWithTarget:(nullable id)target action:(nullable SEL)actionInitialize and add event listener function
  • - (void)addTarget:(id)target action:(SEL)actionAdd event listener function
  • - (void)removeTarget:(nullable id)target action:(nullable SEL)actionDelete event listener function
  • - (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizerAdd other gesture collision invalidator. When the current gesture is triggered, the specified gesture will be invalid.
  • - (CGPoint)locationInView:(nullable UIView*)viewGets the coordinate position relative to the specified view
  • - (CGPoint)locationOfTouch:(NSUInteger)touchIndex inView:(nullable UIView*)viewGets the coordinate position of the specified finger relative to the specified view
Agency agreement
  • - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizerIt is triggered when the gesture is ready to start. If no is returned, the gesture is cancelled.
  • - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizerTriggered when the gesture and other gestures are recognized at the same time, return yes to run the two gestures at the same time, and return no to prevent simultaneous recognition.
  • - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touchWhether to receive a finger for the event. Triggered before the gesture starts to trigger the event. Returning no can prevent the event from acquiring the touched finger.
  • - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceivePress:(UIPress *)pressWhether to receive a finger for the press event, which is triggered before the press gesture event is triggered. Return no to prevent the event from acquiring the touched finger.
We know how to clear the gesturerecognizer class. Let’s learn about the use of gestures in its subclasses.

Uitapgesturerecognizer click gesture

Click gesture to set the number of fingers and the number of clicks to trigger the gesture

//Create click gesture
- (void) createTapGes {
    _ imageView. userInteractionEnabled = YES; //  Turn on response event properties
    UITapGestureRecognizer* tapOneGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(big)]; //  Create gesture
    tapOneGes. numberOfTapsRequired = 1; //  Number of hits to trigger the event
    tapOneGes. numberOfTouchesRequired = 1; //  Number of fingers that trigger the event
    [_imageView addGestureRecognizer:tapOneGes]; //  Add gesture listener
}
//Click to trigger event
- (void) big {
    UIScreen* screen = [UIScreen mainScreen];
    [UIView beginAnimations:nil context:nil]; //  Start layout animation
    _imageView.frame = CGRectMake(0, 0, screen.bounds.size.width, screen.bounds.size.height);
    [UIView commitAnimations]; //  End layout animation
}

Uipinchgesturerecognizer kneading gesture

Kneading gesture indicates that the gesture of two fingers kneading and scaling is triggered. It is often used to listen to picture view and zoom events

//Kneading gesture
- (void) createPinchGes {
    UIPinchGestureRecognizer* pinch = [[UIPinchGestureRecognizer alloc] init]; //  Create gesture
    [pinch addTarget:self action:@selector(scale:)]; //  Add event function
    pinch. delegate = self; //  Set up proxy
    [_imageView addGestureRecognizer:pinch]; //  Add gesture listener to view
}

- (void) scale: (UIPinchGestureRecognizer*) pinch {
    UIView* IView = pinch. view; //  Get the monitored view
    CGAffineTransform transiform = CGAffineTransformScale(IView.transform, pinch.scale, pinch.scale); //  Calculate scaled matrix
    If (transiform.a < 0.4) {// scaling less than 0.4 blocks
        transiform.a = 0.4;
        transiform.d = 0.4;
    }
    IView. transform = transiform; //  Reset matrix
    pinch. scale = 1; //  Reset the zoom matrix, otherwise the gestures will always accumulate
}

//Add proxy function that allows multiple gestures to trigger
- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  YES;
}

In the above code, we get thescaleProperty gets the size of the user’s pinch zoom. And use the built-in APICGAffineTransformScaleRecalculate the 2D matrix of the view (the matrix represents the image deformation. You can learn about graphics). Note! In the last step, you must reset thescaleOtherwise, it will accumulate all the time, resulting in calculation matrix errors. If you do not want to reset, you need to modify itCGAffineTransformScale The first parameter of is the base matrix parameter.

Uirotationgesturerecognizer rotation gesture

Rotate gesture to obtain the rotation angle of the user’s finger.

//Rotation gesture
- (void) createRotateGes {
    UIRotationGestureRecognizer* rotate = [[UIRotationGestureRecognizer alloc] init];
    [rotate addTarget:self action:@selector(rotate:)];
    rotate.delegate = self;
    [_imageView addGestureRecognizer:rotate];
}
//Rotation trigger event
- (void) rotate: (UIRotationGestureRecognizer*) rotate {
    UIView* IView = rotate.view;
    IView. transform =  CGAffineTransformRotate(IView.transform, rotate.rotation); //  Recalculate view matrix
    rotate.rotation = 0;
}

Uipangesturerecognizer pan gesture

The horizontal movement gesture is relatively simple. It is triggered when the finger moves, but it provides the translation position and translation speed

//Pan gesture
- (void) createPanGes {
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    pan.delegate = self;
    [_imageView addGestureRecognizer:pan];
}
- (void) pan: (UIPanGestureRecognizer*)pan {
    CGPoint speed = [pan velocityInView:_imageView]; //  Get movement speed
    Nslog (@ "x speed =%f, y speed =%f", speed.x, speed.y);
    CGPoint translation = [pan translationInView:_imageView]; //  Get move matrix
    CGAffineTransform transform = CGAffineTransformTranslate(_imageView.transform, translation.x, translation.y);
    _imageView.transform = transform;
}

Uilongpressgesturerecognizer long press gesture

Long press the corresponding view to trigger gestures, and set the number of fingers and long press time of fingers

//Long press gesture
- (void) createLongPassGes {
    UILongPressGestureRecognizer* longPass = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pass:)];
    longPass. minimumPressDuration = 1; //  Set long press trigger time, default 0.5
    [_imageView addGestureRecognizer: longPass];
}

- (void)pass: (UILongPressGestureRecognizer*) longPass {
    if (longPass.state == UIGestureRecognizerStateBegan) {
        Nslog (@ "start long press");
    } else if (longPass.state == UIGestureRecognizerStateEnded) {
        Nslog (@ "end long press");
    } else if (longPass.state == UIGestureRecognizerStateChanged) {
        Nslog (@ "long press changes");
    }
}

Uishippegesturerecognizer swipe gesture

Slide gesture, similar to our translation gesture. However, the difference between light sliding and fast sliding is that the user only provides the sliding direction.

//Create a swipe gesture
- (void) createSwipe {
    UISwipeGestureRecognizer* swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swiper:)];
    swipe.direction = UISwipeGestureRecognizerDirectionDown;
    [_imageView addGestureRecognizer: swipe];
    swipe.delegate = self;
}

- (void) swiper: (UISwipeGestureRecognizer*)swiper {
    Nslog (@ "sliding down occurs");
}

Recommended Today

[What is Istio? ] If you don't know, you're out, a 40-minute text can be quickly understood

@[toc] foreword This article is purely theoretical and contains the following content, read it as needed: Istio concepts, service mesh, traffic management, istio architecture (Envoy, Sidecar, Istiod) Virtual Service (VirtualService), Routing Rules, Destination Rules (DestinationRule) Gateway, network resiliency and testing (timeouts, retries, circuit breakers, fault injection) What is Istio? Istio is an open sourceservice mesh, […]