Black Friday deal: 30% off our book "Integrating SwiftUI into UIKit apps"! Learn more ...Black Friday deal:30% off "Integrating SwiftUI into UIKit apps" >>
Quick Tip Icon
Quick Tip

Get tap location in SwiftUI

Starting from iOS 16 and macOS 13, we can get the location of a tap in SwiftUI.

The new onTapGesture(count:coordinateSpace:perform:) overload of onTapGesture() modifier provides the location in its perform closure and allows us to request the location in local or global coordinate space.

struct ContentView: View {
    var body: some View {
        Rectangle()
            .fill(.purple)
            .onTapGesture(coordinateSpace: .local) { location in
                print("Tap location: \(location)")
            }
    }
}

We can also use SpatialTapGesture directly and get the location from the event inside onEnded action closure.

struct ContentView: View {
    var body: some View {
        Rectangle()
            .fill(.purple)
            .gesture(
                SpatialTapGesture()
                    .onEnded { event in
                        print("Tap location: \(event.location)")
                    }
            )
    }
}
Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover
Black Friday offer
Our book "Integrating SwiftUI into UIKit apps" is now 30% off!

Discover various ways to adopt SwiftUI in existing UIKit projects and take full advantage of the new iOS 16 frameworks and APIs such as Swift Charts.

The offer is active until the 1st of December.