【问题标题】:Swift Annotation Custom ImageSwift 注释自定义图像
【发布时间】:2018-07-09 10:42:30
【问题描述】:

我正在使用 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 文件位于我项目的主文件夹中,如下所示:

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

【问题讨论】:

标签: ios swift xcode swift3


【解决方案1】:

这里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

【讨论】:

  • 我应该把这个函数放在 ViewController 中吗?
  • 他在上面提到过:MyAnnotation 是 NSObject 的子类,MKAnnotation。正如您在代码中所做的那样 Annotation.swift
  • 不,我不明白 :( 我应该对 ViewController 和 Annotations.swift 进行哪些更改?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
相关资源
最近更新 更多