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

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

UPDATED FOR iOS 17!

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with new features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit