TheHellOTrofasdasd
TheHellOTrofasdasd

Reputation: 153

uilongpressgesturerecognizer fire only once

I want to add a gesture that will only fire if a person has been pressing for a second or so. Not a tap but a long press. If I use uilongpressgesturerecognizer it keeps firing until I release my finger. How can I get around this.

Upvotes: 7

Views: 2986

Answers (3)

Ronak Chaniyara
Ronak Chaniyara

Reputation: 5435

Set minimumPressDuration when you create and add gesture as below:

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                                      initWithTarget:self action:@selector(handleLongPress:)];
longPress.minimumPressDuration = 1.0;

Write your code in UIGestureRecognizerStateEnded state as below:

-(void)handleLongPress:(UILongPressGestureRecognizer *)Gesture{

    if (Gesture.state == UIGestureRecognizerStateEnded) {


       //Do any thing after long press ended,which will be 1.0 second as set above


    }
    else if (Gesture.state == UIGestureRecognizerStateBegan){



    }
}

Upvotes: 15

ixany
ixany

Reputation: 6040

Swift 5

Declare a UILongPressGestureRecognizer:

let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(gestureAction(gesture:)))

Set its .minimumPressDuration to 1.0 or any interval you want.

Set the recognizers .delegate to your ViewController and add it to your view using .addGestureRecognizer().

Use the following function to handle the gesture:

@objc func gestureAction(gesture: UIGestureRecognizer) {
    if let longPress = gesture as? UILongPressGestureRecognizer {
        if longPress.state == UIGestureRecognizer.State.began {

        } else {

        }
    }
}

Upvotes: 2

Bhadresh Mulsaniya
Bhadresh Mulsaniya

Reputation: 2640

Set value of minimumPressDuration property of UILongPressGestureRecognizer.

Upvotes: 0

Related Questions