Swift: MapKit 自定义图片标注

Swift: MapKit Custom Image Annotation

在我的应用程序中,我有一个 mapkit 和不同颜色的注释。但是,只有三种颜色可供选择(红色、绿色、紫色)。所以,我需要用自定义图像更改注释。

I've followed this tutorial to create my mapview

现在,我有一个 艺术作品 class:

import Foundation
import MapKit

class Artwork: NSObject, MKAnnotation {
    let title: String
    let locationName: String
    let color: String
    let coordinate: CLLocationCoordinate2D

    init(title: String, locationName: String, color: String, coordinate: CLLocationCoordinate2D) {
        self.title = title
        self.locationName = locationName
        self.color = color
        self.coordinate = coordinate

        super.init()
    }

    var subtitle: String {
        return locationName
    }

    // pinColor for disciplines: Sculpture, Plaque, Mural, Monument, other
    func pinColor() -> MKPinAnnotationColor  {
        switch color {
        case "Red":
            return .Red
        case "Purple":
            return .Purple
        case "Green":
            return .Green
        default:
            return .Green
        }
    }
}

此外,VCMapView.swift 文件:

import Foundation
import MapKit

extension MapViewController: MKMapViewDelegate {

    // 1
    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
        if let annotation = annotation as? Artwork {
            let identifier = "pin"
            var view: MKPinAnnotationView
            if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
                as? MKPinAnnotationView { // 2
                    dequeuedView.annotation = annotation
                    view = dequeuedView
            } else {
                // 3
                view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                view.canShowCallout = true
                view.calloutOffset = CGPoint(x: -5, y: 5)
                view.rightCalloutAccessoryView = UIButton.buttonWithType(.DetailDisclosure) as! UIView
            }
            view.pinColor = annotation.pinColor()
            return view
        }
        return nil
    }
}

我可以在 viewdidload()

中像这样在我的地图上添加图钉
// show artwork on map
let artwork = Artwork(title: "\(self.plate)",
locationName: "\(self.location)",
color: "\(self.color)",
coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longtitude))

self.mapView.addAnnotation(artwork)

一切正常,但需要向此架构添加自定义图像,我不确定应该修改哪一部分。

在我看来,在您的体系结构中,您应该在 Artwork class 中添加图像 属性,然后在 .image 属性 中使用 id共 MKPinAnnotationView.

例如:

view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton.buttonWithType(.DetailDisclosure) as! UIView
            }
view.image = UIImage(named:"your_image")
view.frame.size = CGSize(width: 30.0, height: 30.0) //not necessary but just to give you an idea how to resize just in case it is too large.