0

I would like to programmatically launch a UILongPressGesture when a user touches a button. This was asked years ago at How can I send a UILongPressGesture programmatically? but I'm wondering if there's a cleaner or more modern solution.

My existing UILongPressGestureRecognizer code (which maps actual user interactions to functionality) works as follows:

view.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPress)))

where longPress is defined as:

@objc func longPress(sender: UILongPressGestureRecognizer) {
    switch sender.state {
    case .began:
        // Display a 'hover' animation for a specific UIView
        ....
    case .changed:
        // Move existing hover animation
        ...
    default:
        // Complete the hover animation
        ...
    }
}

Desired Functionality

I am using this long press to display a 'hovering' effect for whatever UIView is selected by the user. I also want to provide a button to start the long press automatically (bypassing the longPress where sender.state == .began). My projected solution is programmatically creating the .began long press, creating a gesture object that users can drag around the screen (possibly even translating the UILongPressGestureRecognizer to a UIPanGestureRecognizer if possible), and then continuing the hover animation logic with that new gesture.

Evan Kaminsky
  • 695
  • 10
  • 23
  • Based on your update, what completes the hover animation? And what does "complete" mean here? Do you mean remove the view added when the button is tapped? So far it sounds like you have no need for a long press gesture. Show the "hover" animation when the button it tapped. Use an actual pan gesture so the user can move the view around. Now it's a matter of answering how you want all of this to be stopped. – rmaddy Apr 26 '19 at 03:20
  • 1
    I don't think it is best practice to call Long press gesture manually. What I can suggest you to create 3 functions, one for display hover animation , One for move animation and one for the remove the animation. And You can call all three functions with required arguments to perform the desired animations. Hope it helps – Prashant Tukadiya Apr 26 '19 at 04:41

1 Answers1

0

I found a much cleaner solution to the problem at hand - Replacing the desired button with a UIView containing its own UILongPressGestureRecognizer. I set this gesture's minimumPressDuration to 0 so it behaves equivalently to a button's touchDown event. This new gesture uses the same longPress function from the original question without requiring any additional code to trigger.

Evan Kaminsky
  • 695
  • 10
  • 23