将自定义MKAnnotationView添加到MKPointAnnotation

时间:2015-04-18 02:56:22

标签: ios swift maps mkannotationview

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

    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()

如何将该视图添加到MKPointAnnotation。最初我认为map.addSubview(pointDesc)会起作用。但它没有。

有人有任何建议吗?

1 个答案:

答案 0 :(得分:3)

您需要在自己设计视图的地方实施viewForAnnotation。这是我的应用程序的代码片段,它使用红色删除按钮创建一个简单的视图。您可能会了解如何根据需要实现该目标:

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

}