快速注释自定义图像

时间:2018-07-09 10:42:30

标签: ios swift xcode swift3

我正在使用Swift 3和Xcode 10 beta 3,我需要在地图上的图钉使用自定义图像。在另一个人的帮助下,我们编写了这段代码,除了引脚仍然是默认值之外,所有代码都可以正常工作。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if let annotation = annotation as? Annotation {
            let identifier = "identifier"
            let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView.image = annotation.image //add this
            annotationView.canShowCallout = true
            annotationView.calloutOffset = CGPoint(x: -5, y: 5)
            annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
            return annotationView
        }
        return nil
    }

    let marker = Annotation(title: "LVR" , subtitle: "" , coordinate: CLLocationCoordinate2D(latitude: 43.772523, longitude: 11.254356))
    marker.image = UIImage(named: "antonioli.png")
    //mapView.addAnnotation(marker)
    self.map.addAnnotation(marker)

PNG文件位于我项目的主文件夹中,如下所示: Description

我应该如何处理这个问题?

1 个答案:

答案 0 :(得分:0)

MyAnnotationNSObject, MKAnnotation的子类

func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
    if annotation is MyAnnotation == false
    {

        return nil
    }

    let senderAnnotation = annotation as! MyAnnotation

    let pinReusableIdentifier = senderAnnotation.pinColor.rawValue

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: pinReusableIdentifier)

    if annotationView == nil
    {
        annotationView = MKAnnotationView(annotation: senderAnnotation,                                                                                                reuseIdentifier: pinReusableIdentifier)
        annotationView!.canShowCallout = true

    }
    let pinImage = UIImage(named:"location_curr.png")

    annotationView!.image = pinImage

    return annotationView

}

请参阅演示MapCustomImage