Swift and SwiftUI tutorials for Swift Developers

What’s and how to use LongPressGesture in SwiftUI

Another built-in gesture that the SwiftUI framework has is LongPressGesture. This gesture recognizer allows you to detect a long tap by the user. For example, if you have an image and you want to resize it only when the user presses and holds it for at least a second, you can use LongPressGesture to detect the touch event.

For example, in the following code:

struct ContentView: View {
    
    @State private var isPressed = false
    var body: some View {
        
        Image(systemName: "star.circle.fill")
            .font(.system(size: 200))
            .scaleEffect(isPressed ? 0.5 : 1)
            .foregroundStyle(.green)
            .gesture(
                LongPressGesture(minimumDuration: 1.0)
                    .onEnded({ _ in
                        self.isPressed.toggle()
                    })
                )
    }
}

We have implemented LongPressGesture so that when the image, in this case a star from the SF Symbols library, is pressed by the user for more than a second, it changes its size.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

What's and how to use the gesture modifier in SwiftUI

Next Article

What is the @GestureState property wrapper

Related Posts