首页 > 解决方案 > 将注释链接到标识符 - Swift、MapKit

问题描述

所以,我创建了一个注释。注释出现在我的地图上,但我想更改它的视图。我不确定如何设置它的标识符。

如果您要回答这个问题,请在其中使用我的代码,而不是示例,因为我真的很困惑。

let annotation = MKPointAnnotation()

override func viewDidLoad() {
    super.viewDidLoad()

    let span : MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1)
    let location : CLLocationCoordinate2D = CLLocationCoordinate2DMake(-33.809335, 151.258695)
    let region : MKCoordinateRegion = MKCoordinateRegionMake(location, span)
    mapView.setRegion(region, animated: true)

    annotation.coordinate = location
    annotation.title = "Bus Stop"
    annotation.subtitle = "Street Name at Street Name"
    mapView.addAnnotation(annotation)

}

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

        let identifier = "marker"
        var view: MKMarkerAnnotationView

        if let dequeuedView = mapView.dequeueReusableAnnotationView(
            withIdentifier: identifier)
            as? MKMarkerAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKMarkerAnnotationView(annotation: annotation,
                                          reuseIdentifier: identifier)
            view.markerTintColor = UIColor.blue
            view.glyphImage = UIImage(named: "small-business-20")
            view.selectedGlyphImage = UIImage(named: "small-business-40")
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        }
        return view
}

@IBOutlet weak var mapView: MKMapView!

标签: swiftmapkit

解决方案


您可以使用mapView.view(for:)方法来获取 MKMarkerAnnotationView。

@IBAction func hoge(_ sender: UIButton) {
    if let ann = self.mapView.view(for: annotation) as? MKMarkerAnnotationView {
        ann.glyphImage = UIImage(named: "Laugh")
    }
}

推荐阅读