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

柔情痞子 提交于 2019-12-06 05:42:59

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.

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