将不同的图钉图像与不同的位置相关联 iOS

Associating different pin images with different locations iOS

我有一个包含 4 个位置的数组和一个包含 4 个引脚名称的数组(即 "bluePin.png | redPin.png | etc...")

目前我正在使用我在其他地方找到的一些代码将自定义图钉图形添加到所有 4 个位置,但我所有的图钉都是红色的。

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    let annotationReuseId = "Truck"
    var trkPin = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId)
    if trkPin == nil {
        trkPin = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId)
    } else {
        trkPin!.annotation = annotation
    }
    trkPin!.image = UIImage(named: "redPin.png")
    trkPin!.backgroundColor = UIColor.clearColor()
    trkPin!.canShowCallout = false
    return trkPin
}

如何将引脚颜色与数组中的位置相关联,以便每个位置都按颜色区分?

谢谢!

我通过声明位置数组和数组图像以简单的方式完成了此操作。我有如下 viewDidLoad 方法。

 override func viewDidLoad() {
    super.viewDidLoad()
    self.mapView.delegate = self

    let location = [
        CLLocationCoordinate2D(latitude: 12, longitude: 77),
        CLLocationCoordinate2D(latitude: 12.5, longitude: 77.5),
        CLLocationCoordinate2D(latitude: 13, longitude: 78),
        CLLocationCoordinate2D(latitude: 13.5, longitude: 78)
    ]

    let pins = [
        "red.png",
        "blue.png",
        "green.png",
        "yellow.png"
    ]

    var annotations = [MKPointAnnotation]()
    for (index, eachLocation) in location.enumerate() {
        let pinImageName = pins[index]
        let annotation = MKPointAnnotation()
        annotation.coordinate = eachLocation
        annotation.title = "\(pinImageName)"
        annotations.append(annotation)
    }
    mapView.addAnnotations(annotations)
}

并且在 viewForAnnotation 委托方法中只是从 title 属性 中获取图像名称并明确禁用标注

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationReuseId = "Truck"
    var trkPin = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId)
    if trkPin == nil {
        trkPin = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId)
        trkPin!.canShowCallout = false
    } else {
        trkPin!.annotation = annotation
        if let image = annotation.title {
            trkPin!.image = UIImage(named: image ?? "default.png")
        } else {
            trkPin!.image = UIImage(named: "default.png")
        }
    }
    return trkPin
}