ios 为MKAnnotations设置单个字形文本

nmpmafwu  于 2023-05-23  发布在  iOS
关注(0)|答案(1)|浏览(173)

我想在注解覆盖中使用identifier编号创建MKPointAnnotaion,而不是引脚。因此,第一个注解为1,第二个注解为2,依此类推。
首先,我在UILongPressGestureRecognizer的基础上向mapView添加了MKPointAnnotation
mapView(_:viewFor:)中,我想对这些注解进行样式化。这在一定程度上是可行的,但也给我们带来了问题:
我创建了一个类CustomAnnotation来添加一个identifier到我的MKPointAnnotaion:

class CustomAnnotation: MKPointAnnotation {
    var identifier: Int!
}

我在注册UILongPressGesture时设置了identifier

let annotation = CustomAnnotation()
annotation.identifier = mapView.annotations.count

然后我使用mapView(_:viewFor:)来改变我的MKPointAnnotaion的外观。但是我不知道如何设置annotationView.glyphText,以便它为每个单独创建的注解使用之前定义的identifier

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard annotation is CustomAnnotation else { return nil }

        let annotationView = MKMarkerAnnotationView()
        annotationView.glyphTintColor = .white
        annotationView.glyphText = "44"
            
        return annotationView
    }
}
mnemlml8

mnemlml81#

感谢您@Gerd Castan参考kodeco上的非常广泛的教程
下面我简要给予一下我是如何解决问题的--这可能会对将来的人有所帮助。
首先,我将CustomAnnotation类的类型从MKPointAnnotation更改为MKAnnotation。现在它实际上适用于每个Map Annotation用例。

class CustomAnnotation: NSObject, MKAnnotation {
    @objc dynamic var coordinate: CLLocationCoordinate2D
    var title:String?
    var subtitle: String?
    var identifier: Int?
    
    init(coordinate:CLLocationCoordinate2D,
         title:String?, subtitle:String?, identifier:Int?) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
        self.identifier = identifier
   }
}

然后,我为CustomAnnotation的视图表示创建了一个类,名为CustomAnnotationView。在本例中,类型是MKMarkerAnnotationView,但如果不希望将注解表示为标记,也可以使用MKAnnotationView

class CustomAnnotationView: MKMarkerAnnotationView {
    override var annotation: MKAnnotation?{
        willSet{
            
            guard let marker = newValue as? CustomAnnotation else { return }

            if let number = marker.identifier {
               let alphabeticRepresentation = UnicodeScalar(number+1+64)!
               glyphText = String(alphabeticRepresentation)
            }
            
        }
    }
    
}

上面代码单元格的一个注解:
1.如果您不希望在标记中使用字母表示,则只需删除上面let alphabeticRepresentation = UnicodeScalar(number+1+64)!示例中的以下代码行
在我的UILongPressureGesture处理程序中,我设置了identifier,所以只计算CustomAnnotaion的数量。

let identifier = mapView.annotations.filter{ $0 is CustomAnnotation }.count

在MapViewController的viewDidload()中,我注册了CustomAnnotationView

mapView.register(CustomAnnotationView.self,
                  forAnnotationViewWithReuseIdentifier:
                  MKMapViewDefaultAnnotationViewReuseIdentifier)

就这样

相关问题