Hi there!
I am tying to add and select a map pin using view long press when the gesture is begin.
However after adding and selecting the pin it got deselected immediately, my assumption that it's conflicting when the original map gesture and it's deselecting the pin on the map (like if a pin was selected and you click anywhere on the map to deselect it).
Note that if I increase minimumPressDuration
for the UILongPressGestureRecognizer
it works fine, but I want the value at 0.5 so the pin is quickly added.
here is the full code:
import SwiftUI
import MapKit
struct ContentView: View {
@State var selection: CustomMapSelection?
@State private var longPressPosition: CGPoint = .zero
@State private var pinCoordinate: CLLocationCoordinate2D?
var body: some View {
MapReader { proxy in
Map(selection: $selection) {
if let pinCoordinate {
Marker("Custom Location", coordinate: pinCoordinate)
.tag(CustomMapSelection(coordinate: pinCoordinate))
}
}
.gesture(LongPressGestureRecognizer(position: $longPressPosition))
.onChange(of: longPressPosition) {
if let coordinate = proxy.convert(longPressPosition, from: .global) {
pinCoordinate = coordinate
selection = CustomMapSelection(coordinate: coordinate)
}
}
}
}
}
struct CustomMapSelection: Hashable {
let latitude: Double
let longitude: Double
init(coordinate: CLLocationCoordinate2D) {
latitude = coordinate.latitude
longitude = coordinate.longitude
}
}
struct LongPressGestureRecognizer: UIGestureRecognizerRepresentable {
@Binding var position: CGPoint
func makeCoordinator(converter: CoordinateSpaceConverter) -> Coordinator {
Coordinator()
}
func makeUIGestureRecognizer(context: Context) -> UILongPressGestureRecognizer {
let recognizer = UILongPressGestureRecognizer()
recognizer.delegate = context.coordinator
// if you make the minimumPressDuration above 2, it works fine and the selection doesn't cancel
recognizer.minimumPressDuration = 0.5
return recognizer
}
func handleUIGestureRecognizerAction(_ recognizer: UILongPressGestureRecognizer, context: Context) {
if recognizer.state == .began {
let position = recognizer.location(in: recognizer.view)
self.position = position
}
}
class Coordinator: NSObject, UIGestureRecognizerDelegate {
func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
return true
}
}
}
#Preview {
ContentView()
}
@FarouKz There are several gestures available on Maps, such as pan, swipe, drag, tap, long press, and a few others, which are enabled in different contexts depending on various settings. It’s not recommended to add additional gestures, as they are likely to conflict with system gestures. Moreover, you cannot override system gestures to replace them with your own implementation.