简体   繁体   中英

Set annotation's glyphtext based on the annotation's properties

I'm running into an issue with custom annotations displaying incorrectly. In my code, I check whether the current annotation is for a station with a given unique identifier. If so, I customize its properties.

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

At first, my mapView displays the annotations correctly (ie, changing the color and glyphtext for the only station with station.id == 26 ), but after panning and zooming for a while, my custom formatting begins to get applied to other annotations (which shouldn't happen, because there's only one station for any given station.id ). I suspect it's due to the AnnotationView reusing the annotation. How can I prevent this from happening?

As you said, it's due to the AnnotationView reusing the annotation. Try the following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM