SwiftUI Long Press: How To Guide

The Long Press gesture, as the name suggests, is triggered when a user presses and holds a view for a certain duration. This Long Press gesture is often used when you want to drag and drop something or to show additional information.

SwiftUI provides a dedicated gesture modifier, .onLongPressGesture, to recognize and respond to long press interactions. In this blog post, we will use .onLongPressGesture to execute a function and change the duration of how long you have to press before the action executes.

How to add a Long Press Gesture in SwiftUI

We will start with a basic example where we create an Image view displaying an SF Image — when you press and hold the image we will print “Long pressed”:

import SwiftUI

struct LongPressView: View {
    var body: some View {
        Image(systemName: "button.horizontal.top.press.fill")
            .font(.system(size: 100))
            .onLongPressGesture() {
                print("Long pressed")
            }
    }
}

That is how you implement the long press gesture in SwifUI, it’s quite easy and you can use it on any view.

Change the longpressgesture duration

The default implementation of the .onLongPressGesture modifier works just fine in many use cases, but sometimes you might want to change the duration. The default pressure time is 0.5 seconds.

In the following example, we will create the same .onLongPressGesture as above but we will change the duration to 2 seconds:

import SwiftUI

struct LongPressView: View {
    var body: some View {
        Image(systemName: "button.horizontal.top.press.fill")
            .font(.system(size: 100))
            .onLongPressGesture(minimumDuration: 2) {
                print("Long pressed")
            }
    }
}

Change the distance you can move to cancel

ThemaximumDistance is a property of the onLongPressGesture modifier that specifies the maximum distance in points that a user can move their finger while performing a long press gesture without canceling the gesture.

By default, the distance is set to 10 CGFloat points.

In the following example, we expand the distance to 100:

import SwiftUI

struct LongPressView: View {
    var body: some View {
        Image(systemName: "button.horizontal.top.press.fill")
            .font(.system(size: 100))
            .onLongPressGesture(maximumDistance: 100) {
                print("Long pressed")
            }
    }
}

Wrap up Long Press in SwiftUI

The long press gesture can be used in many different scenarios and as you just read it’s quite easy to implement the.onLongPressGesture.

In this blog post we covered how you implement and use .onLongPressGesture.I hope you can use this in your next application — happy coding 🙂

Scroll to Top