I want to display a dynamic label on custom pin. I used MKMapView, CLLocationManager,MKAnnotationView and MKPinAnnotationView. So, please help me friends.
Like:

I want to display a dynamic label on custom pin. I used MKMapView, CLLocationManager,MKAnnotationView and MKPinAnnotationView. So, please help me friends.
Like:

First create a custom MKAnnotationView based class:
Swift 3
class CustomAnnotationView: MKAnnotationView {
var label: UILabel?
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Then make sure your ViewController class adds NKMapViewDelegate as a delegate:
Swift 3
import UIKit
import MapKit
class ViewController: MKMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
}
Then add the following method to your ViewController which will be called by the MapView whenever an annotation is added to the map:
Swift 3
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationIdentifier = "MyCustomAnnotation"
guard !annotation.isKind(of: MKUserLocation.self) else {
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)
if annotationView == nil {
annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
if case let annotationView as CustomAnnotationView = annotationView {
annotationView.isEnabled = true
annotationView.canShowCallout = false
annotationView.label = UILabel(frame: CGRect(x: -5.5, y: 11.0, width: 22.0, height: 16.5))
if let label = annotationView.label {
label.font = UIFont(name: "HelveticaNeue", size: 16.0)
label.textAlignment = .center
label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
label.adjustsFontSizeToFitWidth = true
annotationView.addSubview(label)
}
}
}
if case let annotationView as CustomAnnotationView = annotationView {
annotationView.annotation = annotation
annotationView.image = #imageLiteral(resourceName: "YourPinImage")
if let title = annotation.title,
let label = annotationView.label {
label.text = title
}
}
return annotationView
}
Once you've done all this, the annotation can be added like this:
Swift 3
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: /* latitude */, longitude: /* longitude */)
annotation.title = "Your Pin Title"
mapView.addAnnotation(annotation)
If you mean you want the pin to have a letter on it then you need to set the image of the annotation view in viewForAnnotation. If you're planning to change the pin for each annotation you'll need to create the image dynamically. They will be plenty of code around this but it comes down to this
annotationView.image = anImage;