Search code examples
iosswiftannotationsmkmapviewmkannotation

Won't Show Custom Pin Image


Im trying to make Custom Pin Images to show up in my mapView and it's presenting the regular red pin instead of my Custom Image. What am i doing wrong?

ViewFor Annotation:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            return nil
        }
        let reuseID = "pin"
        
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID) as? MKPinAnnotationView
        if(pinView == nil) {
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
            pinView!.canShowCallout = true
            pinView!.animatesDrop = false
            pinView?.image = UIImage(named: "CustomPinImage")
            pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIButton
            let smallSquare = CGSize(width: 40, height: 40)
            let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
            button.setBackgroundImage(UIImage(named: "Car2"), for: UIControlState())
            pinView?.leftCalloutAccessoryView = button
            
        }
        else
        {
            pinView?.annotation = annotation
        }
        
        return pinView
        
    }

How I'm displaying Pins :

let LitzmanLocation = CLLocationCoordinate2DMake(32.100668,34.775192)
        let Litzman = MKPointAnnotation()
        Litzman.coordinate = LitzmanLocation
        Litzman.title = "Litzman Bar"
        Litzman.subtitle = "נמל תל אביב 18,תל אביב"
        mapView.addAnnotation(Litzman)

It would be great if anyone could help me sort this out !

Thank you :)


Solution

  • Try this code :

     func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    
            if annotation.isMember(of: MKUserLocation.self) {
                return nil
            }
    
            let reuseId = "pin"
    
            var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
            if pinView == nil {
                pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)}
            pinView!.canShowCallout = true
            pinView!.image = UIImage(named: "CustomPinImage")
            pinView?.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIButton
            let smallSquare = CGSize(width: 40, height: 40)
            let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
            button.setBackgroundImage(UIImage(named: "Car2"), for: UIControlState())
            pinView?.leftCalloutAccessoryView = button
    
            return pinView
    
        }