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
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.
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
MKAnnotationView *annotationView = [views objectAtIndex:0];
id<MKAnnotation> mp = [annotationView annotation];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,350,350);
[mv setRegion:region animated:YES];
[mapView selectAnnotation:mp animated:YES];
}
if you are doing the same thing which is calling the setRegion method, then make sure that you call
[mapView selectAnnotation:mp animated:YES];
after
[mv setRegion:region animated:YES];
The method to call is "selectAnnotation:animated" from MKMapView.
Starting in iOS 11, there is a new type of MKAnnotationView called MKMarkerAnnotationView, which can display title and subtitle without being selected. Check https://developer.apple.com/documentation/mapkit/mkmarkerannotationview
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
if #available(iOS 11.0, *) {
let annoView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "HunterAnno")
annoView.canShowCallout = true
return annoView
}
let annoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "HunterAnnoLow")
annoView.canShowCallout = true
return annoView
}