Change image to MKMapView in Swift

I am trying to change the pin image to MKMapView in Swift, but unfortunately it does not work. Any idea what I'm doing wrong? I saw a few examples here, but didn't work.

import UIKit import MapKit class AlarmMapViewController: UIViewController { @IBOutlet weak var map: MKMapView! override func viewDidLoad() { super.viewDidLoad() showAlarms() map.showsUserLocation = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func showAlarms(){ map.region.center.latitude = 49 map.region.center.longitude = 12 map.region.span.latitudeDelta = 1 map.region.span.longitudeDelta = 1 for alarm in Alarms.sharedInstance.alarms { let location = CLLocationCoordinate2D( latitude: Double(alarm.latitude), longitude: Double(alarm.longtitude) ) let annotation = MKPointAnnotation() annotation.setCoordinate(location) annotation.title = alarm.name annotation.subtitle = alarm.description mapView(map, viewForAnnotation: annotation).annotation = annotation map.addAnnotation(annotation) } } @IBAction func zoomIn(sender: AnyObject) { } @IBAction func changeMapType(sender: AnyObject) { } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if annotation is MKUserLocation { //return nil so map view draws "blue dot" for standard user location return nil } let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = true pinView!.animatesDrop = true pinView!.image = UIImage(named:"GreenDot")! } else { pinView!.annotation = annotation } return pinView } } 

Image GreenDot is available and used in other places.

+7
ios swift
source share
2 answers

Do not forget to install:

 map.delegate = self 

And make sure your UIViewController implements the MKMapViewDelegate protocol.
If you forget to do this, your implementation of mapView:viewForAnnotation: will not be called for your map.

Also, it looks like pinView!.animatesDrop = true breaking custom images. You must set it to false or use MKAnnotationView (which does not have the animatesDrop property).

See this related question if you want to implement custom drop animation.

+17
source share

MKPinAnnotationView always uses a pin image, cannot be undone. Instead, you should use MKAnnotationView. Be aware, because the animatesDrop property is not a valid MKAnnotationView property, a Rem string.

+7
source share

All Articles