我正在尝试让
SwiftUI
+ MapKit
+ LongPress
手势正常工作。当我在 ContentView
中添加地图时,效果很好。然后,我将 .onLongPressGesture
修改器添加到地图中,平移/缩放停止工作。长按还是可以的。
我正在编写的代码:
Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true)
.onLongPressGesture {
// How do I get the location (Lat/Long) I am pressed on?
print("onLongPressGesture")
}
另外,有没有办法从长按手势获取纬度/经度?
希望仅使用
SwiftUI
使其工作,而不将 UIKit
包裹在 UIViewRepresentable
中。
不要问为什么,但这似乎有效:
Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true)
.gesture(DragGesture())
.onLongPressGesture {
print("Here!")
}
是的。
我将
MKMapView
包裹在 UIViewRepresentable
中,并在委托方法中添加了长按手势识别器,如下所示:
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
// We need to update the region when the user changes it
// otherwise when we zoom the mapview will return to its original region
DispatchQueue.main.async {
if self.longPress == nil {
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGesture(recognizer:)))
mapView.addGestureRecognizer(recognizer)
self.longPress = recognizer
}
self.parent.region = mapView.region
}
}
然后
@objc func longPressGesture(recognizer: UILongPressGestureRecognizer) {
if let mapView = recognizer.view as? MKMapView {
let touchPoint = recognizer.location(in: mapView)
let touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
// TODO: check if we already have this location and bail out
if annotations.count > 0 {
return
}
let annotation = Annotation(title: touchMapCoordinate.stringValue, coordinate: touchMapCoordinate)
mapView.removeAnnotations(annotations.compactMap({ $0.pointAnnotation }))
annotations.append(annotation)
mapView.addAnnotation(annotation.pointAnnotation)
}
}
回答您问题的最后一部分 - Paul Hudson 在此页面
上展示了如何获取纬度/经度中的点击(或长按)位置 MapReader { proxy in
Map()
.onTapGesture { position in
if let coordinate = proxy.convert(position, from: .local) {
print(coordinate)
}
}
}