ios – 在Swift和MapKit中使用MKPinAnnotationView()

我有一个工作循环为一些工作数据点设置标题和字幕元素的注释.在同一循环结构中我想做的是将引脚颜色设置为紫色而不是默认值.我不知道的是,我需要做的是点击我的mapView来相应地设置引脚.

我的工作循环和某些尝试…

....
for var index = 0; index < MySupplierData.count; ++index {

  // Establish an Annotation
  myAnnotation = MKPointAnnotation();
  ... establish the coordinate,title,subtitle properties - this all works
  self.theMapView.addAnnotation(myAnnotation)  // this works great.

  // In thinking about PinView and how to set it up I have this...
  myPinView = MKPinAnnotationView();      
  myPinView.animatesDrop = true;
  myPinView.pinColor = MKPinAnnotationColor.Purple;  

  // Now how do I get this view to be used for this particular Annotation in theMapView that I am iterating through??? Somehow I need to marry them or know how to replace these attributes directly without the above code for each data point added to the view
  // It would be nice to have some kind of addPinView.  

}

解决方法

您需要实现viewForAnnotation委托方法并返回一个MKAnnotationView(或子类).
这就像在Objective-C中 – 底层SDK的工作方式相同.

从添加注释的for循环中删除MKPinAnnotationView的创建,并实现代理方法.

以下是Swift中的ViewForAnnotation委托方法的示例实现:

func mapView(mapView: MKMapView!,viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {

    if annotation is MKUserLocation {
        //return nil so map view draws "blue dot" for standard user location
        return nil
    }

    let reuseId = "pin"

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation,reuseIdentifier: reuseId)
        pinView!.canShowCallout = true
        pinView!.animatesDrop = true
        pinView!.pinColor = .Purple
    }
    else {
        pinView!.annotation = annotation
    }

    return pinView
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...