【问题标题】:How to change the color of a MKPointAnnotation in Swift 5?如何在 Swift 5 中更改 MKPointAnnotation 的颜色?
【发布时间】:2020-11-14 21:01:22
【问题描述】:

我想以绿色显示基于特定列表的注释。我该怎么做?这是我的代码:

for i in closestpharmacyname{
    var docref2 = db.collection("pharmacies").document(i)
    print("Pharmacy: ", i)
    docref2.getDocument(source: .cache) { (document, error) in
        if var document  = document {
            var pharmacylatitude = document.get("latitude") as! Double
            var pharmacylongitude = document.get("longitude") as! Double
            print(pharmacylatitude, pharmacylongitude)
                             
            var pharmacyannotation = MKPointAnnotation()
            pharmacyannotation.coordinate = CLLocationCoordinate2D(latitude: pharmacylatitude, longitude: pharmacylongitude)
            pharmacyannotation.title = i
                    
            self.MapView.addAnnotation(pharmacyannotation)
        }else{
            print("Document does not exist")
        }
    }
}

一切正常,除了注释是标准的红色。

【问题讨论】:

    标签: ios swift xcode mapkit mkannotation


    【解决方案1】:

    尝试改用 MKMarkerAnnotationView,这样您就可以自定义颜色。据我所知,不可能更改 MKPointAnnotation 的颜色。 MKMarkerAnnotationView 看起来也一样。

    更具体地说,您需要添加此函数,据我了解,该函数接受 MKPointAnnotation 并返回一个 MKMarkerAnnotationView,您可以自定义每个,这意味着您可以使用 switch 语句有条件地为每个注释赋予不同的颜色。

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "something")
        annotationView.markerTintColor = .green //custom colors also work, additionally to these default ones
        return annotationView
    }
    

    为了更好地理解自定义注释,包括图片中的自定义符号而不是默认符号,请查看此链接: https://medium.com/better-programming/how-to-customize-mapkit-annotations-baad32487a7

    【讨论】:

      猜你喜欢
      • 2022-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 2017-05-21
      • 2020-01-26
      相关资源
      最近更新 更多