【问题标题】:Remove annotations containing a title equal/not equal to a String?删除包含标题等于/不等于字符串的注释?
【发布时间】:2017-03-28 08:57:37
【问题描述】:

我已经寻找了几天试图删除标题等于或不等于从另一个视图控制器的 uicollection 视图单元 didSelect 中选择的字符串的注释。我将字符串传递给包含我的地图视图的视图控制器。我使用自定义注释,它是注释显示方式的模型。

如何按标题选择和删除自定义注释。我已经有一个字典数组,其中包含删除其他注释后注释将使用的数据。我知道如何删除所有注释,但不知道如何仅删除标题等于/不等于搜索字符串的注释。

为什么 swift 3 没有这样的功能?

我想出了这个,但只删除了注释并显示了“filteredAnnotations”

 var filteredAnnotations = self.mapview.annotations.filter {($0.title != nil) && isEqual(searchString) }

 print(filteredAnnotations)

 self.mapview.removeAnnotations(self.mapview.annotations)
 self.mapview.addAnnotations(filteredAnnotations)

使用 print 语句只返回一个空数组“[]”

【问题讨论】:

  • 让filteredAnnotations = mapview.annotations.filter {注解 if let title = annotation.title, title != searchString { return true } return false } mapview.removeAnnotations(filteredAnnotations)

标签: swift search filter annotations title


【解决方案1】:

使用filter 获取应删除的所有注释的列表(即标题不是您的搜索字符串,但也不是MKUserLocation),然后删除它们。

在 Swift 3 中:

let filteredAnnotations = mapView.annotations.filter { annotation in
    if annotation is MKUserLocation { return false }          // don't remove MKUserLocation
    guard let title = annotation.title else { return false }  // don't remove annotations without any title
    return title != searchString                              // remove those whose title does not match search string
}

mapView.removeAnnotations(filteredAnnotations)

显然,将 != 更改为 == 以满足您的要求或其他,但这说明了使用 filter 来识别一组标题与某些特定标准匹配的注释的基本思想。

对于 Swift 2,请参阅 previous revision of this answer

【讨论】:

  • 天哪,谢谢罗伯。那工作得很好。我还在习惯那个过滤器功能。有时代码提示/代码完成只会创造更多的谜团。
  • 好的,如果你想删除那些标题不匹配的,那么当然使用!=。但请记住,您只想删除自己的注释(即,如果删除 MKUserLocation,可能会产生奇怪的副作用),因此也要从过滤结果中排除 MKUserLocation
  • 没有 MKUSerLocation 声明它工作得很好。因为我有 MKUserLocation Pin/Annotation 的自定义注释。如果您转到另一个不是“filterVC”的viewController,它也会返回所有注释,正如我所期望的那样。如何清除过滤器并返回所有注释?再次感谢顺便说一句
  • 您应该只删除您明确添加的注释,因此删除 MKUserLocation 仍然是一个错误,恕我直言,但您可以随心所欲。但很明显,如果您不使用MKUserLocation,则不必担心。只是大多数人忽略了它(特别是因为副作用是如此微妙)。
  • 如果你想重新添加过滤后的注解,只需将该数组保存在某个属性中,稍后再执行addAnnotations
猜你喜欢
  • 2015-06-09
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
  • 2015-04-22
  • 2015-03-08
  • 2012-01-27
相关资源
最近更新 更多