Detecting Long Press Gestures in SwiftUI
Written by Team Kodeco
Have you ever wanted to detect when a user performs a long press on a view in your SwiftUI app? Luckily for us, SwiftUI provides a simple and easy-to-use gesture to detect long press gestures. In this cookbook entry, you’ll learn how to use this gesture to detect long presses on a view.
Let’s start by creating a simple SwiftUI view that we can add a long press gesture to. Open up Xcode and create a new SwiftUI View file, then add the following code:
struct ContentView: View {
var body: some View {
Text("Tap and hold me!")
.padding()
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(10)
.onLongPressGesture(minimumDuration: 1) {
print("Long press detected!")
}
}
}
Your preview should look like this:
Here’s what’s happening in this code:
The Text
creates a label with the text “Tap and hold me!”. The padding
modifier adds padding around the text. The background
modifier with Color.blue
sets the background of the view to blue, while the foregroundColor
modifier sets the text color to white. The cornerRadius
modifier rounds the corners of the view.
After setting up the visual aspects of the view, you add a .onLongPressGesture
modifier. This modifier is used to detect long press gestures on the view. The minimumDuration
argument indicates the minimum duration (in seconds) that qualifies as a long press; here it’s set to 1 second. The closure attached to this gesture is called when the long press is detected. In this case, it prints “Long press detected!” to the console.
So, when a user taps and holds the blue box in the view for at least one second, “Long press detected!” will be output to the console. This offers a straightforward way to handle long press gestures in your SwiftUI applications.