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