Replace icon pin by text label in annotation?

后端 未结 2 1011
逝去的感伤
逝去的感伤 2020-12-03 11:01

Is it possible to replace the pin icon of an annotation by a dynamic text label?

Maybe using css, or dynamically creating an image?

For example a label is do

2条回答
  •  再見小時候
    2020-12-03 11:37

    Here's a Swift 3 variation of the delegate method mentioned in Anna's comment above. Make sure your class conforms to MKMapViewDelegate and that the mapView's delegate is set to self in viewDidLoad().

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            return nil
        }
    
        let reuseId = "reuseid"
        var av = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        if av == nil {
            av = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
            lbl.backgroundColor = .black
            lbl.textColor = .white
            lbl.alpha = 0.5
            lbl.tag = 42
            av?.addSubview(lbl)
            av?.canShowCallout = true
            av?.frame = lbl.frame
        }
        else {
            av?.annotation = annotation
        }
    
        let lbl = av?.viewWithTag(42) as! UILabel
        lbl.text = annotation.title!
    
        return av
    }
    

提交回复
热议问题