在Swift中更改MKMapView上的引脚图像
我试图在Swift中更改MKMapView上的引脚图像,但不幸的是它不工作。 任何想法我做错了什么? 我在这里看到了一些例子,但没有奏效。
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 } }
GreenDot图片可用并在其他地方使用。
不要忘记设置:
map.delegate = self
并确保你的UIViewController
实现MKMapViewDelegate
协议。
如果你忘了这样做,你的mapView:viewForAnnotation:
将不会被调用。
此外,它看起来像pinView!.animatesDrop = true
打破自定义图像。 你必须将它设置为false
,或者使用MKAnnotationView
(它没有MKAnnotationView
属性)。
看到这个相关的问题,如果你想实现自定义放下animation。
MKPinAnnotationView总是使用一个pin图像,不能被执行。 您必须改用MKAnnotationView。 请注意,因为属性animatesDrop它不是一个有效的MKAnnotationView的属性,Rem行。