gpt4 book ai didi

ios - 将自定义 MKAnnotationView 添加到 MKPointAnnotation

转载 作者:可可西里 更新时间:2023-11-01 01:06:05 38 4
gpt4 key购买 nike

我正在尝试使用 swift 创建一个 iOS 应用程序,它在 map View 上创建注释。在大多数情况下,我已经完成了,但是,我正在尝试创建一个自定义 View ,当用户点击图钉时弹出该 View 。这是放置注释的代码:

    let point = MKPointAnnotation()

//This isn't the actual location
let location = CLLocationCoordinate2DMake(1, 1)

point.coordinate = location
point.title = "Title"
point.subtitle = "Description"
map.addAnnotation(point)
map.centerCoordinate = point.coordinate

let mapCamera = MKMapCamera()
mapCamera.centerCoordinate = location
mapCamera.altitude = 300
mapCamera.heading = 180

self.map.camera = mapCamera

此代码将图钉放置在正确的位置。但是,假设我有一个 MKAnnotationView 对象,它有一个像这样的红色背景:

let pointDesc = MKAnnotationView()
pointDesc.backgroundColor = UIColor.redColor()

如何将该 View 添加到 MKPointAnnotation。最初我认为 map.addSubview(pointDesc) 会起作用。但事实并非如此。

有人有什么建议吗?

最佳答案

您需要在您自己设计的 View 中实现viewForAnnotation。这是我的应用程序中的一个代码片段,它创建了一个带有红色删除按钮的简单 View 。您可能会了解如何根据您的需要实现它:

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {   
if annotation is PinAnnotation { // PinAnnotation is my custom annotation class
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

关于ios - 将自定义 MKAnnotationView 添加到 MKPointAnnotation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712380/

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