NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to add a gesture recognizer to a view

Paul Hudson    @twostraws   

Updated for Xcode 12.5

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 smaller every time it’s tapped:

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

    var body: some View {
        Image("ireland")
            .scaleEffect(scale)   
            .gesture(
                TapGesture()
                    .onEnded { _ in
                        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 halves in size when pressed for at least one second:

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

    var body: some View {
        Image("cornwall")
            .scaleEffect(scale)
            .gesture(
                LongPressGesture(minimumDuration: 1)
                    .onEnded { _ in
                        scale /= 2
                    }
            )
    }
}

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 the user moves it at least 50 points:

struct ContentView: View {
    @State private var dragCompleted = false

    var body: some View {
        VStack {
            Image("iceland")
                .gesture(
                    DragGesture(minimumDistance: 50)
                        .onEnded { _ in
                            dragCompleted = true
                        }
                )

            if dragCompleted {
                Text("Drag completed!")
            }
        }
    }
}

Drag gestures are particularly good when combined with the offset() modifier, which lets us adjust the natural position of a view. For example, this offsets an image using a dragOffset size, which itself is attached to a drag gesture:

struct ContentView: View {
    @State private var dragOffset = CGSize.zero

    var body: some View {
        VStack {
            Image("rome")
                .offset(dragOffset)
                .gesture(
                    DragGesture()
                        .onChanged { gesture in
                            dragOffset = gesture.translation
                        }
                        .onEnded { gesture in
                            dragOffset = .zero
                        }
                )
        }
    }
}

If you try that code you’ll see you can drag the image around now, and when you release your finger it snaps back to its original location.

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.4/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.