Swift and SwiftUI tutorials for Swift Developers

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

The SwiftUI framework includes numerous modifiers, such as the tap gesture. Additionally, there are gestures such as DragGesture, MagnificationGesture, and LongPressGesture.

In other tutorials, we have used the onTapGesture modifier to handle the user’s tap and provide feedback.

In this article, we will explore the gesture modifier.

To recognize a particular gesture in SwiftUI, you can attach a gesture recognizer to a view using the .gesture modifier. Here is a code snippet that attaches a TapGesture using the .gesture modifier.

var body: some View {
    Image(systemName: "star.circle.fill")
        .font(.system(size: 200))
        .foregroundStyle(.green)
        .gesture(
            TapGesture()
                .onEnded({
                    print("Tapped!")
                })
        )
}

This way every time the user taps on the star, “Tapped!” will be printed to the console.

This would be the result in XCode:

Leave a Reply

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

Previous Article

How to show multiple options with ConfirmationDialog() in SwiftUI

Next Article

What's and how to use LongPressGesture in SwiftUI

Related Posts