Search code examples
iosswiftannotationsmapkitmkpinannotationview

Cant set Custom Pin Image In MapView, Swift 3


Mini-Map Code:

import UIKit
import MapKit

@IBOutlet weak var ProfileMapView: MKMapView!

func mapView(_ ProfileMapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation.isMember(of: MKUserLocation.self) {
        return nil
    }

    let reuseId = "ProfilePinView"

    var pinView = ProfileMapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
    if pinView == nil {
        pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
    }
    pinView!.canShowCallout = true
    pinView!.image = UIImage(named: "CustomPinImage")
    return pinView
}

override func viewDidLoad() {
    super.viewDidLoad()
    let LightHouseLocation = CoordinatesTemplate
    // Drop a pin
    let lightHouse = MKPointAnnotation()
    lightHouse.coordinate = LightHouseLocation
    lightHouse.title = barNameTemplate
    lightHouse.subtitle = streetNameTemplate
    ProfileMapView.addAnnotation(lightHouse)
}

why doesn't it work? why i can't get my custom image to work as the pin image? it works on another view controller for me. thanks ahead


Solution

  • Your issue is that you´re missing add your UIViewController as delegate of your MKMapView so you need to add this line in your viewDidLoad as I said in my comments

    self.ProfileMapView.delegate = self
    

    I also recommend you to use the extension pattern to make your code more readable

    extension YourViewController : MKMapViewDelegate{
    
        func mapView(_ ProfileMapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    
            if annotation.isMember(of: MKUserLocation.self) {
                return nil
            }
    
            let reuseId = "ProfilePinView"
    
            var pinView = ProfileMapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
            if pinView == nil {
                pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)}
            pinView!.canShowCallout = true
            pinView!.image = UIImage(named: "CustomPinImage")
    
            return pinView
    
        }
    }