Search code examples
iosswiftmapsmkannotationview

Adding a custom MKAnnotationView to a MKPointAnnotation


I'm trying to create an iOS app with swift which creates an annotation on a map view. For the most part I have done it, however, I am trying to create a custom view which pops up when the user taps on the pin. Here is the code which places the annotation:

    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

This code places the pin at the right location. However, say I had a MKAnnotationView object which had a red background like so:

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

How could I add that view to the MKPointAnnotation. Originally I thought map.addSubview(pointDesc) would work. But it doesn't.

Does anybody have any suggestions?


Solution

  • You need to implement viewForAnnotation where you design that view youself. This is a code snippet from my app which creates a simple view with a red delete button. You might get the idea on how to implement that for your needs:

    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
    

    }