Longer subtitles in MapView annotations (swift)

2020-03-30 03:34发布

问题:

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?

回答1:

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
}