在Swift中更改MKMapView上的图钉图像

max*_*xxo 8 ios swift

我试图在Swift中改变MKMapView上的pin图像,但不幸的是它不起作用.任何想法我做错了什么?我在这里看到了一些例子,但没有奏效.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

GreenDot图片可在其他地方使用.

Par*_*ara 17

别忘了设置:

map.delegate = self
Run Code Online (Sandbox Code Playgroud)

并确保您UIViewController实现MKMapViewDelegate协议.
如果您忘记执行此操作,mapView:viewForAnnotation:则不会为您的地图调用您的实现.

此外,它看起来像pinView!.animatesDrop = true打破自定义图像.您必须将其设置为false或使用MKAnnotationView(没有animatesDrop属性).

如果要实现自定义拖放动画,请参阅此相关问题.

  • 您是否尝试过使用`MKAnnotationView`代替`MKPinAnnotationView`? (3认同)

小智 9

MKPinAnnotationView总是使用pin图像,不能永远.您必须使用MKAnnotationView.请注意,因为属性animatesDrop它不是有效的MKAnnotationView的属性,Rem该行.