首页 > 解决方案 > Mapbox:注释更改时刷新annotationView

问题描述

我有自定义注释,有时会在它们上方显示一个 textView。如果我的注释上名为 text 的变量为零,它们不会显示 textView。

注释可能有要显示的文本,但在显示注释时文本变量的值可能会发生变化。在这种情况下,我希望刷新注释,使其不再显示 textView。

我已经有一个委托函数,如果设置了注释文本变量,则使用 textView 创建注释;如果未设置注释的文本变量,则创建不带 textView 的注释,它的工作原理是这样的,尽管这不是实际代码

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView?{
    if annotation is MyCustomAnnotation{
        if annotation.hasText(){
            return MyCustomAnnotationView(hasText: True)
        }else{
            return ViewWithoutTextView(hasText: False)
        }
    }

但是,如果在注释已经显示时注释从有文本变为没有文本或反之亦然,那么我不知道如何刷新它或再次调用它以便显示正确的注释视图

标签: iosswiftmapbox

解决方案


正如@Magnas 在评论中所说,您必须删除注释并重新添加它以更新状态。

最好创建一个自定义注释视图,该视图具有处理隐藏/显示其中的文本视图的逻辑。然后,您只需保留注释的引用并通过 更新它,annotationView而完全不经历和弄乱地图注释。

一个粗略的例子(很多空白要填充):

// your methods in your custom annotation. Use these wherever you want to change things
class CustomAnnotation: MGLAnnotationView {
  func showText() { }
  func hideText() { }
}

// Define data structure to access your annotation with some kind of key
dataSourceToAnnotationView: [String: CustomAnnotation]


// save your annotations so you can access them later
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {        
  var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "customReuseId")
  if annotationView == nil {
    annotationView = CustomAnnotation()
    let key = "exampleKeyString"
    dataSourceToAnnotationView[key] = annotationView as! CustomAnnotation
  }
    
  return annotationView
}

推荐阅读