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

送分小仙女□ 提交于 2019-12-22 17:14:27

问题


I have looked for a couple of days on trying to remove annotations that a title equal or not equal to a string that is selected from a uicollection View cell didSelect from another view controller. I get the string passed to my view controller that contains my mapview. I use a custom annotation that is the model for how the annotations are displayed.

How do I select and remove the custom annotations by their title. I already have an array of dictionaries that contains the data the annotations will use once the other annotations are removed. I know how to remove ALL the annotations, but not how to just remove the ones that have titles that are equal/not equal to the search string.

Why is nothing on the web or current for swift 3 for such a function?

I have come up with this, but only removed annotations and does display the "filteredAnnotations"

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

 print(filteredAnnotations)

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

using the print statement only returns an empty array of "[]"


回答1:


Use filter to get a list of all annotations that should be removed (i.e. whose title is not your search string, but isn't a MKUserLocation, either) and then remove them.

In 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)

Obviously, change that != to == as suits your requirements, or whatever, but this illustrates the basic idea of using filter to identify a set of annotations whose title matches some particular criteria.

For Swift 2, see previous revision of this answer.



来源:https://stackoverflow.com/questions/40593539/remove-annotations-containing-a-title-equal-not-equal-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!