iosswiftuigesturerecognizeruilongpressgesturerecogni

Swift Programmatically Launch a UILongPressGesture


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.


Solution

  • 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.