2

I have a mapView with annotations displaying titles and subtitles. The subtitles are sometimes longer than the width of the annotation, so I am wondering if i can make them multiline? It's coded like this so far:

func annotate(newCoordinate, title: String, subtitle: String) {
    let annotation = MKPointAnnotation()
    annotation.coordinate = newCoordinate
    annotation.title = title
    annotation.subtitle = subtitle
    self.map.addAnnotation(annotation)    
}

Then i have a few options set in

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {...}

which are not relevant here.

Is it posible to make a custom annotation view? I've tried a couple of things, but nothing worked. The closest I can get is adding a button to display the longer subtitle separately, but i'd rather have it inside the annotation.

Is it possible?

2

1 Answer 1

12

I figured it out, I added a label in viewForAnnotation and it just worked

¯\_(ツ)_/¯

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is MKUserLocation {
        //return nil so map view draws "blue dot" for standard user location
        return nil
    }

    let reuseId = "pin"

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView!.canShowCallout = true
    }
    else {
        pinView!.annotation = annotation
    }

    //THIS IS THE GOOD BIT
    let subtitleView = UILabel()
    subtitleView.font = subtitleView.font.fontWithSize(12)
    subtitleView.numberOfLines = 0
    subtitleView.text = annotation.subtitle!
    pinView!.detailCalloutAccessoryView = subtitleView


    return pinView
}
1
  • Good answer, but "detailCalloutAccessoryView" is available since 9.0 Sep 27, 2016 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.