gpt4 book ai didi

ios - 如何快速在MKMapview上显示MKPinAnnotationView

转载 作者:搜寻专家 更新时间:2023-10-31 22:50:40 25 4
gpt4 key购买 nike

我正在尝试在 MKMapView 中的图钉上实现自定义注释 View 。另一个用户给了我这个函数来生成自定义的 MKPinAnnotationView。 https://stackoverflow.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

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

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

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

谢谢!

最佳答案

在你的问题中,你谈到了 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)方法,但由您直接调用。

map View (MKMapView) 将调用它并向函数传递参数等。

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

要确保 map View 调用您的委托(delegate)方法,您必须:

  • 确保 map View 的 delegate 导出连接到 Storyboard中的 View Controller ,或者
  • 在代码中,通常在 viewDidLoad 中,执行 mapView.delegate = self


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

所以这一行:

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

应该是这样的:

map.addAnnotation(point)

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


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

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

关于ios - 如何快速在MKMapview上显示MKPinAnnotationView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29714784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com