小编典典

坚持在Swift和MapKit中使用MKPinAnnotationView()

swift

我有一个工作循环来为一些工作数据点设置标题和字幕元素的注释。我想要在相同的循环结构中执行的操作是将图钉颜色设置为“紫色”,而不是默认值。我不知道要怎么做才能进入我的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.

}

阅读 284

收藏
2020-07-07

共1个答案

小编典典

您需要实现viewForAnnotation委托方法并MKAnnotationView从那里返回一个(或子类)。
就像在Objective-C中一样-基础SDK的工作方式相同。

MKPinAnnotationViewfor添加注释的循环中删除创建的内容,并改为实现委托方法。

这是viewForAnnotationSwift中委托方法的示例实现:

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
}
2020-07-07