iPhone iOS how to add a UILongPressGestureRecognizer and UITapGestureRecognizer to the same control and prevent conflict?

前端 未结 5 514
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 19:25

I\'m building an iPhone app that would let the user rearrange some of the UI elements on the screen.

How can I add a tap gesture recognizer and a long press gesture rec

5条回答
  •  野性不改
    2021-02-01 19:43

    To combine successfully both you need:

    1º Add to interface gesture delegate at header

    @interface ViewController : ViewController 
    

    2º Create gesture events and add to a view into source file:

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touch:)];
        [tap setNumberOfTapsRequired:1]; // Set your own number here
        [tap setDelegate:self]; // Add the  protocol
    
        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTouch:)];
        [longTap setNumberOfTapsRequired:0]; // Set your own number here
        [longTap setMinimumPressDuration:1.0];
        [longTap setDelegate:self]; // Add the  protocol
        [tap requireGestureRecognizerToFail:longTap];   // Priority long
    
        [self.view addGestureRecognizer:tap];
        [self.view addGestureRecognizer:longTap];
    

    3º Add callbacks in source file:

    - (void) touch: (UITapGestureRecognizer *)recognizer
    {
        CGPoint location = [recognizer locationInView: self.HUDview];
        if (recognizer.state == UIGestureRecognizerStateBegan)
        {
            NSLog(@"touch UIGestureRecognizerStateBegan");
        }
        if (recognizer.state == UIGestureRecognizerStateEnded)
        {
            NSLog(@"touch UIGestureRecognizerStateEnded");
            //NSLog(@"Position of touch: %.3f, %.3f", location.x, location.y);    // Position landscape
        }
    }
    
    - (void) longTouch: (UILongPressGestureRecognizer *)recognizer
    {
        if (recognizer.state == UIGestureRecognizerStateBegan)
        {
            NSLog(@"longTouch UIGestureRecognizerStateBegan");
        }
        if (recognizer.state == UIGestureRecognizerStateEnded)
        {
            NSLog(@"longTouch UIGestureRecognizerStateEnded");
        }
    }
    

    4º Set gesture recognizer available:

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    {
        return YES;
    }
    

提交回复
热议问题