首页 > 解决方案 > SwiftUI Map 长按注解

问题描述

用户如何通过长按向地图添加注释?我无法从地图视图中获取位置(纬度、经度)?你能通过 SwiftUI 解释一下吗?

let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(addAnnotationOnLongPress(gesture:)))

longPressGesture.minimumPressDuration = 1.0 self.mapView.addGestureRecognizer(longPressGesture)

@objc func addAnnotationOnLongPress(gesture: UILongPressGestureRecognizer) {

if gesture.state == .ended {
    let point = gesture.location(in: self.mapView)
    let coordinate = self.mapView.convert(point, toCoordinateFrom: self.mapView)
    print(coordinate)
    //Now use this coordinate to add annotation on map.
    var annotation = MKPointAnnotation()
    annotation.coordinate = coordinate
    //Set title and subtitle if you want
    annotation.title = "Title" 
    annotation.subtitle = "subtitle" 
    self.mapView.addAnnotation(annotation)
}

}

我该如何使用它,例如通过 SWIFTUI 的 UILongPressGestureRecognizer?谢谢

标签: swiftuiannotationsapple-maps

解决方案


推荐阅读