NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...
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

Check out our new book!

Swift Gems

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

Swift Gems

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

  • 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
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift