how to change pin color in mapkit under the same annotationview (swift3)

别等时光非礼了梦想. 提交于 2019-12-01 13:04:17

问题


I have 2 pins in mapkit, both are under the same annotation view so it makes since that both of the pins are the same color. How can I make the pins different colors. I would like hello to be red and hellox to be blue.

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

@IBOutlet var jmap: MKMapView!

override func viewDidLoad() {
    jmap.delegate = self;
    let hello = MKPointAnnotation()
    hello.coordinate = CLLocationCoordinate2D(latitude: 40, longitude: -73)
    jmap.addAnnotation(hello)
    let hellox = MKPointAnnotation()
    hellox.coordinate = CLLocationCoordinate2D(latitude: 34, longitude: -72)
    jmap.addAnnotation(hellox)
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationView = MKPinAnnotationView()
    annotationView.pinTintColor = .blue
    return annotationView
}}

回答1:


Subclass MKPointAnnotation to add any custom property that you want, such as a pinTintColor:

class MyPointAnnotation : MKPointAnnotation {
    var pinTintColor: UIColor?
}

class ViewController: UIViewController, MKMapViewDelegate {
    @IBOutlet var jmap: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        jmap.delegate = self

        let hello = MyPointAnnotation()
        hello.coordinate = CLLocationCoordinate2D(latitude: 40, longitude: -73)
        hello.pinTintColor = .red

        let hellox = MyPointAnnotation()
        hellox.coordinate = CLLocationCoordinate2D(latitude: 34, longitude: -72)
        hellox.pinTintColor = .blue

        jmap.addAnnotation(hello)
        jmap.addAnnotation(hellox)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as? MKPinAnnotationView

        if annotationView == nil {
            annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotation")
        } else {
            annotationView?.annotation = annotation
        }

        if let annotation = annotation as? MyPointAnnotation {
            annotationView?.pinTintColor = annotation.pinTintColor
        }

        return annotationView
    }
}


来源:https://stackoverflow.com/questions/41819940/how-to-change-pin-color-in-mapkit-under-the-same-annotationview-swift3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!