首页 > 解决方案 > Swift 地图图钉标注和参数

问题描述

我使用 MapKit 在我的 iOS 应用程序上制作了一张地图。

我使用标注按钮将我的图钉添加到我的视图中,该按钮在图钉弹出窗口中显示详细信息按钮。

此时,一切都很好,当我点击详细信息按钮时,我可以打印一些文本,呈现一个新的视图控制器,但我的问题是我无法弄清楚我如何知道我点击了哪个引脚。

我可以通过使用标题来解决它,但这对我来说不是最好的方法,我更喜欢使用我的项目 ID 而不是字符串。

如果有人知道我如何在我的 pin 上添加“id”属性或使用 subtitle 属性(不在弹出气泡上显示),我将不胜感激:)

谢谢您的帮助。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customAnnotation")
    annotationView.image = UIImage(named: "pin")
    annotationView.canShowCallout = true
    annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)

    return annotationView
}


func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl){

    print("OK, item tapped.")
}

标签: swiftmapkitmkpinannotationview

解决方案


您可以子类MKPointAnnotation化以添加ID属性

class CustomPointAnnotation: MKPointAnnotation {
    let id: Int

    init(id: Int) {
        self.id = id
    }
}

用法

let annotation = CustomPointAnnotation(id: INTEGER)
annotation.coordinate = CLLocationCoordinate2D(latitude: DOUBLE, longitude: DOUBLE)
mapView.addAnnotation(annotation)

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if let annotation = view.annotation as? CustomPointAnnotation {
        print("Annotation \(annotation.id)")
    }
}

MKAnnotation您还可以通过扩展基本协议来创建自己的注释类,如下所示:

class CustomAnnotation: NSObject, MKAnnotation {
    let id: Int
    let coordinate: CLLocationCoordinate2D

    init(id: Int, latitude: Double, longitude: Double) {
        self.id = id
        self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

推荐阅读