Setup:
I am converting an app to SwiftUI. This app had an MKMapView
with annotations that could be dragged on the map.
I was able to write a first version of the SwiftUI app with a draggable image.
It uses a View
that is displayed as annotation on the map:
struct AnnotationView: View {
var buyLocationNameBeforeDragging: String
@State private var isDragging = false
@GestureState var dragAmount = CGSize.zero
var region: MKCoordinateRegion
func coordinateFrom(region: MKCoordinateRegion, dragAmount: CGSize) -> CLLocationCoordinate2D {
let coordinate = CLLocationCoordinate2D() // How to compute this?
return coordinate
}
var drag: some Gesture {
DragGesture()
.onChanged { _ in
self.isDragging = true
}
.onEnded { _ in
self.isDragging = false
let coreDataManager = testOrPreview ? CoreDataManager.test : CoreDataManager.shared
let newCoordinate = coordinateFrom(region: region, dragAmount: dragAmount)
// Move the dragged place to the new coordinate
// …
}
.updating($dragAmount) { value, state, transaction in
state = value.translation
}
}
var body: some View {
Image("PinRed")
.offset(dragAmount)
.defersSystemGestures(on: .all)
.onTapGesture {
print("tapped")
}
.gesture(drag)
}
}
It is possible to tap the annotation pin, and - after tapping longer - to drag the pin to a new location.
Problem:
To update my model, I need the endpoint coordinates of the drag on the map. These should be computed in func coordinateFrom
(see above), but I have no idea how to do this.
MKMapView
has e.g. a function convert(_:toCoordinateFrom:)
, but SwiftUI's Map
has nothing like this.
Question:
How to do the conversion?