Longer subtitles in MapView annotations (swift)

廉价感情. 提交于 2020-01-11 06:58:10

问题


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
}


来源:https://stackoverflow.com/questions/37772535/longer-subtitles-in-mapview-annotations-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!