NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to add a gesture recognizer to a view

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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!")
            }
    )

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5