【问题标题】:Stuck on using MKPinAnnotationView() within Swift and MapKit坚持在 Swift 和 MapKit 中使用 MKPinAnnotationView()
【发布时间】:2014-08-22 19:21:28
【问题描述】:

我有一个工作循环来为某些工作数据点的标题和副标题元素设置注释。我想要在同一个循环结构中做的是将引脚颜色设置为紫色而不是默认值。我无法弄清楚的是我需要做什么才能进入我的 theMapView 以相应地设置引脚。

我的工作循环和一些尝试......

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

}

【问题讨论】:

    标签: ios mkmapview swift mapkit mkannotationview


    【解决方案1】:

    您需要实现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
    }
    

    【讨论】:

    • 辉煌 - Tks。我把这个直接放进去,它奏效了。我只需要看到一个 Swift 等价物,因为我没有做很多 Obj C。一个小问题是编译器在该行中使用下划线发出警告:func mapView(_ mapView: MKMapView!,...警告是参数“mapView”中的“Extraneous“_”没有关键字参数名称。
    • @Anna,你有可用的示例项目吗?我在这里用头撞墙。谢谢
    • 我没有足够的代表发表评论,但上面的功能仍然有效,除了 pinView!.pinColor 没有贬值。它应该是 pinView!.pinTintColor = UIColor.purpleColor()
    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多