删除包含等于字符串的标题 equal/not 的注释?

Remove annotations containing a title equal/not equal to a String?

我找了几天试图从另一个视图控制器的 uicollection 视图单元格 didSelect 中删除标题等于或不等于 selected 的字符串的注释。我将字符串传递到包含我的 mapview 的视图控制器。我使用自定义注释作为注释显示方式的模型。

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

为什么 swift3 这样的功能在网络上或当前没有任何内容?

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

 var filteredAnnotations = self.mapview.annotations.filter {([=11=].title != nil) && isEqual(searchString) }

 print(filteredAnnotations)

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

仅使用 print 语句 returns 空数组“[]”

使用 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