【问题标题】:Set annotation's glyphtext based on the annotation's properties根据注解的属性设置注解的字形
【发布时间】:2026-01-29 04:20:03
【问题描述】:

我遇到了自定义注释显示不正确的问题。在我的代码中,我检查当前注释是否用于具有给定唯一标识符的站。如果是这样,我会自定义它的属性。

StationAnnotationView.swift

class StationAnnotationView: MKMarkerAnnotationView {

override var annotation: MKAnnotation? {
    willSet {
        guard let station = newValue as? Station else { return }

        clusteringIdentifier = nil
        displayPriority = .required

        if (station.id == "26") {
                glyphText = "p"
                markerTintColor = UIColor(named: "Blue")
        }
    }
}

起初,我的mapView 正确显示注释(即,更改具有station.id == 26 的唯一站的颜色和字形),但在平移和缩放一段时间后,我的自定义格式开始应用于其他注释(这不应该发生,因为任何给定的station.id 只有一个站)。我怀疑这是由于 AnnotationView 重用了注释。我怎样才能防止这种情况发生?

【问题讨论】:

    标签: swift annotations mapkit mkannotationview reuseidentifier


    【解决方案1】:

    正如您所说,这是由于 AnnotationView 重用了注释。试试下面的代码:

        if (station.id == "26") {
                glyphText = "p"
                markerTintColor = UIColor(named: "Blue")
        } else {
                glyphText = // Default text
                markerTintColor = // Default color
        }
    

    【讨论】:

    • 解决了。我不明白为什么,但确实如此。谢谢。