简体   繁体   English

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

[英]Stuck on using MKPinAnnotationView() within Swift and MapKit

I have a working loop to setup annotations for the title and subtitle elements for some working data points. 我有一个工作循环来为一些工作数据点的标题和副标题元素设置注释。 What I want to do within that same loop structure is to set the pin color to Purple instead of the default. 我想在同一个循环结构中做的是将引脚颜色设置为紫色而不是默认值。 What I can't figure out is what I need to do to tap into my theMapView to set the pin accordingly. 我无法弄清楚我需要做些什么来点击我的theMapView来相应地设置引脚。

My working loop and some attempts at something... 我的工作循环和一些尝试......

....
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.  

}

You need to implement the viewForAnnotation delegate method and return an MKAnnotationView (or subclass) from there. 您需要实现viewForAnnotation委托方法并从那里返回MKAnnotationView (或子类)。
This is just like in Objective-C -- the underlying SDK works the same way. 这与Objective-C类似 - 底层SDK的工作方式相同。

Remove the creation of MKPinAnnotationView from the for loop that adds the annotations and implement the delegate method instead. for循环中删除MKPinAnnotationView的创建,该循环添加注释并实现委托方法。

Here is a sample implementation of the viewForAnnotation delegate method in Swift: 以下是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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM