How to Automatically Display Title/Subtitle on Map Annotation (pin)

后端 未结 4 1988
甜味超标
甜味超标 2020-12-31 10:19

I am loading an annotation onto my map view. The annotation displays as a pin when the map is loaded.

However, the title and subtitle do not appear on the pin automa

4条回答
  •  心在旅途
    2020-12-31 10:42

    Adding a follow-up answer (that is applicable to Xcode 11.4 and Swift 5), as I had this exact problem, but the above answers did not work. @zsani is correct in that you need to use MKMarkerAnnotationView (as opposed to MKPinAnnotationView) to get both, but you also have to set the titleVisibility and subtitleVisibility properties (although titleVisibility seems to be on by default with MKMarkerAnnotationView).

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        // do not alter user location marker
        guard !annotation.isKind(of: MKUserLocation.self) else { return nil }
    
        // get existing marker
        var view = mapView.dequeueReusableAnnotationView(withIdentifier: "reuseIdentifier") as? MKMarkerAnnotationView
    
        // is this a new marker (i.e. nil)?
        if view == nil {
            view = MKMarkerAnnotationView(annotation: nil, reuseIdentifier: "reuseIdentifier")
        }
    
        // set subtitle to show without being selected
        view?.subtitleVisibility = .visible
    
        // just for fun, show green markers where subtitles exist; red otherwise
        if let _ = annotation.subtitle! {
            view?.markerTintColor = UIColor.green
        } else {
            view?.markerTintColor = UIColor.red
        }
    
        return view
    }
    

    Sharing in case anyone else has this same problem.

提交回复
热议问题