如何让用户添加自定义注释?

How to let user to add custom annotation?

我找不到任何文档、视频或 Whosebug 答案。

这是我的问题。我创建了地图并添加到我的自定义 MKAnnotation 和 MKAnnotationView 中。

我想让用户创建自定义 pin 并通过 CoreData 保存到本地

MyCustomAnnotation 具有相同的属性,即标题、副标题和坐标。

我想出的第一个解决方案是放置一个按钮,该按钮创建一个可拖动到用户位置的图钉。

但我需要获得不那么复杂、更复杂的解决方案。

private func addPins() {
    let list = PrivateLocations.shared.initLocations()
    for pin in list {
        map.addAnnotation(pin)
    }
}

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    if view.annotation is MKUserLocation { return }
    let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
    let customView = views?[0] as! CustomCalloutView
    customView.delegate = self
    customView.isUserInteractionEnabled = true
    customView.titleLabel.text = view.annotation?.title!
    customView.desc.text = view.annotation?.subtitle!
    customView.center = CGPoint(x: view.bounds.size.width / 2, y: -customView.bounds.size.height*0.52)
    view.addSubview(customView)
    map.setCenter((view.annotation?.coordinate)!, animated: true)
}

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is MKUserLocation {
        return nil
    } else {
        let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "CustomAnnotationView")
        annotationView.image = UIImage(named: "myImage")
        annotationView.canShowCallout = false
        return annotationView
    }
}

最后是我的 CustomPin class :

var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?

init(_ title: String, _ subtitle: String, _ coordinate: CLLocationCoordinate2D) {
    self.title = title
    self.subtitle = subtitle
    self.coordinate = coordinate
}

我就是这样解决这个问题的,

1) 为用户显示创建一个 UIView,他想在其中添加注释。

2) 添加一个平移手势识别器。

func addPanGesture(view: UIView) {
    let pan = UIPanGestureRecognizer(target: self, action: #selector (self.handlePan(sender:)))
    view.addGestureRecognizer(pan)
}

3) 在我的选择器函数中,我调用了 pinDropped() func

  @objc func handlePan(sender: UIPanGestureRecognizer) {

    let view = sender.view!
    let translation = sender.translation(in: self.mapView)

    switch sender.state {
    case .began, .changed:
        pinImage.center = CGPoint(x: dropPinImage.center.x + translation.x, y: dropPinImage.center.y + translation.y)
        sender.setTranslation(CGPoint.zero, in: view)
        break
    default:
        pinDropped()
        break
    }
}

4) 我在我的 pinDropped 函数中写下了将要发生的事情

func pinDropped() {
    DispatchQueue.main.async {
        let pin = CustomPin(self.lastOrigin, "pin")
        self.mapView.addAnnotation(pin)
    }
    self.saveButton.alpha = 1
    pinImage.alpha = 0
}