swift 如何在 MKMapview 上显示 MKPinAnnotationView

How to display MKPinAnnotationView on MKMapview in swift

我正在尝试在 MKMapView 中的图钉上实现自定义注释视图。另一个用户给了我这个函数来生成自定义的 MKPinAnnotationView。 https://whosebug.com/users/3845091/zisoft

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is PinAnnotation {
    let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")

    pinAnnotationView.pinColor = .Purple
    pinAnnotationView.draggable = true
    pinAnnotationView.canShowCallout = true
    pinAnnotationView.animatesDrop = true

    let deleteButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
    deleteButton.frame.size.width = 44
    deleteButton.frame.size.height = 44
    deleteButton.backgroundColor = UIColor.redColor()
    deleteButton.setImage(UIImage(named: "trash"), forState: .Normal)

    pinAnnotationView.leftCalloutAccessoryView = deleteButton

    return pinAnnotationView
}

return nil

}

我会向函数传递我想要的地图参数和我想要自定义的注释。即 mapView(myMap, viewForAnnotation: point)

这一切都很好而且很有意义,但是,当我尝试使用
map.addAnnotation(mapView(myMap, viewForAnnotation: point)) 将 MKPinAnnotationView 添加到地图时
它错误地指出数据类型无效。有人知道如何使用自定义视图在地图上物理渲染图钉吗?

简单的解决方案总是最好的。

谢谢!

在你的问题中,你说的是 viewForAnnotation 方法:

And I would pass the function the parameters of the map I want it on and the annotation I want to customise. i.e. mapView(myMap, viewForAnnotation: point)

不,这是错误的。

不会给函数传递参数等

那个 viewForAnnotation 方法是您实现的 delegate 方法,但 不是 直接由您调用。

地图视图 (MKMapView) 将调用它并向函数传递参数等

viewForAnnotation 委托方法是您可以为给定注释 model 对象提供自定义 view 的地方。

要确保地图视图调用您的委托方法,您必须:

  • 确保地图视图的 delegate 出口连接到故事板中的视图控制器,或者
  • 在代码中,通常在 viewDidLoad 中执行 mapView.delegate = self.


当您调用 addAnnotation 时,您将注解 model 对象传递给它(例如 MKPointAnnotation 或任何实现 MKAnnotation 协议的对象)。

所以这一行:

map.addAnnotation(mapView(myMap, viewForAnnotation: point))

应该是这样的:

map.addAnnotation(point)

MKPinAnnotationView 对象(以及子类 MKAnnotationView 的任何对象)是某些注释的 view model object -- 它们不是一回事。


这些问题和主题已经在 iOS 和 MapKit 文档、SO 和其他地方的教程中多次提及。

以下是一些您可能会觉得有用的关于 SO 的相关问题:

  • Stuck on using MKPinAnnotationView() within Swift and MapKit
  • viewForAnnotation confusion and customizing the pinColor iteratively