Long Press Detection in SwiftUI
In this tutorial, we will learn how to detect long press in SwiftUI.
In order to do this, I will create a simple image view and on clicking on that image for more than a specific time it will do some action.
Detect long press on an image in SwiftUI
Image(systemName: "heart.fill") .foregroundStyle(show ? Color.red : Color.green) .font(.system(size: 100))
This is our image view. Now I will add .gesture
modifier and use LongPressGesture()
function to change the color of the image when long press happens.
Let’s check it:
import SwiftUI struct ContentView: View { @GestureState var press = false @State var show = false var body: some View { Image(systemName: "heart.fill") .foregroundStyle(show ? Color.red : Color.green) .font(.system(size: 100)) .gesture( LongPressGesture(minimumDuration: 0.5) .onEnded { _ in show.toggle() print("Hi i am Pressed") } ) } }
Output:
I have brought the simulator near the console to show you the detection.
.gesture( LongPressGesture(minimumDuration: 0.5) .onEnded { _ in show.toggle() print("Hi i am Pressed") } )
As you can see I have added a print function just to show you that long press detected. This will only print it in the console if you press the image for more than 0.5 seconds.
LongPressGesture(minimumDuration: 0.5)
in this line I have declared the duration in seconds which is 0.5 here.
If you press the edges of the screen you might get warning in the console. I have written a separate article on that: Gesture: System gesture gate timed out. in SwiftUI
Long press detection on a button
Previously I have used .gesture for images. But for the button it won’t work. You will need to use .simultaneousGesture
instead of that.
Let’s see an example of how I can detect a long press for a button.
import SwiftUI struct ContentView: View { @GestureState var press = false @State var show = false var body: some View { Button(action: {}) { Text("Press me for long") } .simultaneousGesture( LongPressGesture(minimumDuration: 2) .onEnded { _ in print("I am pressed for long") } ) } }
Output:
In this way, you can do the button action and long press action at the same time.
If you wish you can remove the minimumDuration
as well for using the default long-time duration.
Also check my other tutorials:
Leave a Reply