NEW: Learn SwiftUI with my free YouTube video series! >>

< How to read tap and double-tap gestures   How to respond to view lifecycle events: onAppear and onDisappear >

How to add a gesture recognizer to a view

Any SwiftUI view can have gesture recognizers attached, and those gesture recognizers in turn can have closures attached that will be run when the recognizer activates.

There are several gesture recognizers to work with, and I’m going to provide you with code samples for several of them to help get you started – you’ll see how similar they are.

First, TapGesture. When you create this you can specify how many taps it takes to trigger the gesture, then attach an onEnded closure that will be run when the gesture happens. For example, this creates an image that gets bigger every time it’s tapped:

struct ContentView: View {
    @State private var scale: CGFloat = 1.0

    var body: some View {
        Image("example-image")
            .scaleEffect(scale)

            .gesture(
                TapGesture()
                    .onEnded { _ in
                        self.scale += 0.1
                    }
            )
    }
}

Second, LongPressGesture recognizes when the user presses and holds on a view for at least a period of time you specify. So, this creates an image view that prints a message when its pressed for at least two seconds:

Image("example-image")
    .gesture(
        LongPressGesture(minimumDuration: 2)
            .onEnded { _ in
                print("Pressed!")
        }
    )

Finally, DragGesture triggers when the user presses down on a view and move at least a certain distance away. So, this creates an image with a drag gesture that triggers when they move it at least 50 points:

Image("example-image")
    .gesture(
        DragGesture(minimumDistance: 50)
            .onEnded { _ in
                print("Dragged!")
            }
    )

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< How to read tap and double-tap gestures   How to respond to view lifecycle events: onAppear and onDisappear >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.5/5

Click here to visit the Hacking with Swift store >>