Join our newsletter! Get Swift & SwiftUI tips, project updates, and discounts on our books...JOIN OUR NEWSLETTER!Monthly Swift insights, updates, and deals...
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)")
                    }
            )
    }
}
Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35