SwiftUI 4 added support to track tap location, it’s a CGPoint type which gives us the exact location of a tap. By default, provided location comes from local coordinate system of the view.
Let’s create an example where we will create an orange circle which will animate to the tap location.
struct TapGestureLocationExample: View {
@State private var pos = CGPoint(x: 100, y: 100) var body: some View {
VStack {
Circle()
.fill(Color.orange.gradient)
.frame(width: 50)
.position(pos)
Spacer()
}
.background(Color.gray.opacity(0.3))
.onTapGesture { location in
withAnimation(Animation.easeOut(duration: 2)) {
pos = location
}
}
}
}
We can specify coordinate system with the following statement:
.onTapGesture(coordinateSpace: .global)
Let’s update our code:
struct TapGestureLocationExample: View {
@State private var pos = CGPoint(x: 100, y: 100) var body: some View {
Circle()
.fill(Color.orange.gradient)
.frame(width: 50)
.position(pos)
.onTapGesture(coordinateSpace: .global) { location in
withAnimation(Animation.easeOut(duration: 2)) {
pos = location
}
}
}
}
With that we have reached the end of this article. Thank you once again for reading. Also subscribe our newsletter at https://www.devtechie.com