how to show multiple lines in MKAnnotation with autolayout?

后端 未结 6 1892
臣服心动
臣服心动 2020-12-30 17:21

i am using mapkit how i can multiple line in MKAnnotation view.

Every annotation there has title and subtitle. how i show sub title with

6条回答
  •  时光取名叫无心
    2020-12-30 17:57

    5 steps

    I created a label and added it to the annotationView?.detailCalloutAccessoryView property (step 5). I also set the label's text to the annotation.subtitle text (step 2 & step 4) and .numberOfLines = 0

    Steps are in the comments above the code

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    
        if annotation.isKindOfClass(MKUserLocation) {
            return nil
        }
    
        let reuseIdentifier = "reuseIdentifier"
    
        var annotationView = mapView.mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? MKPinAnnotationView
    
        if annotationView == nil {
    
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
    
            // 1. set the annotationView's canShowCallout property to true
            annotationView?.canShowCallout = true
    
            // 2. get the subtitle text from the annontation's subtitle property
            let subtitleText = annotation.subtitle ?? "you have no subtitle"
    
            // 3. create a label for the subtitle text
            let subtitleLabel = UILabel()
            subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
    
            // 4. set the subtitle's text to the label's text property and number of lines to 0
            subtitleLabel.text = subtitleText
            subtitleLabel.numberOfLines = 0
    
            // 5. set the annotation's detailCalloutAccessoryView property to the subtitleLabel
            annotationView?.detailCalloutAccessoryView = subtitleLabel
    
        } else {
            annotationView!.annotation = annotation
        }
    
        return annotationView
    }
    

提交回复
热议问题