ios - 如何在同一注释 View (swift3)下更改mapkit中的引脚颜色

标签 ios swift swift3 mapkit mkannotationview

我在 mapkit 中有 2 个图钉,它们都在相同的注释 View 下,因为两个图钉的颜色相同。我怎样才能让别针有不同的颜色。我希望 hello 是红色的,hellox 是蓝色的。

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

最佳答案

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

关于ios - 如何在同一注释 View (swift3)下更改mapkit中的引脚颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819940/

相关文章:

iphone - Swift - TableView 如何创建可扩展部分

swift - 在 View 之间传递核心数据 swift

ios - 数据使用和 Firebase 查询

ios - 强制用户在 iOS 中以编程方式更新应用程序

ios - UIButton 在第一次运行时工作正常,但在模拟器上第二次运行时不起作用

ios - 在两个 View 之间共享一个 NSString

ios - 在 Xcode 10 中对 Xcode 项目文件进行排序,以清除项目文件更改

ios - 可重用的 Swift 扩展和选择器

swift - 使用 SFSpeechRecognizer 的单个口语字母?

ios - Swift 3.0 如何在 firebase 的父对象上添加子对象