iosswift3mkpinannotationview

assign image to annotation instead of pin


Hi Guys I am trying to replace the pin on my annotation to a custom image.

I already have the images in my image.cassette list will displays 1X 2X 3X etc. but as soon as I try to call that image I get an error in my code where Xcode tries to fix my syntax but eventually throws it out as error

my code listed below override func

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

    guard !(annotation is MKUserLocation) else {
        return nil
    }


    let annotationIdentifier = "AnnotationIdentifier"

    var annotationView: MKAnnotationView?
    if let dequeuedAnnotationView =   mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
        annotationView = dequeuedAnnotationView
        annotationView?.annotation = annotation
    }
    else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
        annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
    }

    if let annotationView = annotationView {

        annotationView.canShowCallout = true
        annotationView.image = UIImage(named: "House")
    }

    return annotationView
}

Now Xcode is picking up an error here in code annotationView.image = UIImage(named: "House") where it ask to insert "," and the end result looks like this

annotationView.image = UIImage(named: "#imageLiteral(resourceName: ",House,")")

Xcode will then display an error use of unresolved identifier 'House'


Solution

  • Swift 3 introduces Image Literals. Just write "Imag".. and it opens popup with Image Literal option. like below image:

    enter image description here

    By selecting "Image Literal" option, It will popup all available assets images,

    enter image description here

    Select image you want to use from the grid.

    for more details, see this