Search code examples
iosswiftswift3mkmapviewmapkit

How to add title and subtitle to my annotations in swift 3?


I've tried to add title and subtitle to my annotations, but all my attempts had failed. Please help me!

import UIKit
import MapKit

class MyPointAnnotation : MKPointAnnotation{
    var pinTintColor: UIColor?

}

class MapViewController: UIViewController, MKMapViewDelegate {


    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self;


        let hello = MyPointAnnotation()
        hello.coordinate = CLLocationCoordinate2D(latitude: 46.771210, longitude: 23.623635)
        hello.title = "tile"
        hello.subtitle = "subtitle"

        hello.pinTintColor = .blue

        let hellox = MyPointAnnotation()
        hellox.coordinate = CLLocationCoordinate2D(latitude: 44.426767, longitude: 26.102538)
        hellox.pinTintColor = .blue

        mapView.addAnnotation(hello)
        mapView.addAnnotation(hellox)
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as? MKPinAnnotationView

        if annotationView == nil {
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotation")
        } else {
            annotationView?.annotation = annotation
        }

        if let annotation = annotation as? MyPointAnnotation {
            if #available(iOS 9.0, *) {
                annotationView?.pinTintColor = annotation.pinTintColor
            } else {
                // Fallback on earlier versions
            }
        }

        return annotationView
    }
}

Solution

  • You need set canShowCallout true to show title and subtitle.

    Try the following code.

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as? MKPinAnnotationView
    
        if annotationView == nil {
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotation")
            annotationView?.canShowCallout = true
        } else {
            annotationView?.annotation = annotation
        }
    
        if let annotation = annotation as? MyPointAnnotation {
            if #available(iOS 9.0, *) {
                annotationView?.pinTintColor = annotation.pinTintColor
            } else {
                // Fallback on earlier versions
            }
        }
    
        return annotationView
    }