如何在同一注解视图

如何在同一注解视图

本文介绍了如何在同一注解视图(swift3)下的mapkit中更改图钉颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mapkit中有2个图钉,它们都在同一个注解视图下,因此,由于两个图钉的颜色相同,所以它可以使之成为现实.如何使别针颜色不同.我希望你好是红色,而你好是蓝色.

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
}}

推荐答案

子类,以添加所需的任何自定义属性,例如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
    }
}

这篇关于如何在同一注解视图(swift3)下的mapkit中更改图钉颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:36