Swift-MapView重复注释
我正在从FireStore查询数据,并在MapView上显示元素,使用光标可以对数据进行分页 这是我的自定义注释类:Swift-MapView重复注释,swift,mapkit,mkmapview,mapkitannotation,Swift,Mapkit,Mkmapview,Mapkitannotation,我正在从FireStore查询数据,并在MapView上显示元素,使用光标可以对数据进行分页 这是我的自定义注释类: final class PostAnnotation: NSObject, MKAnnotation { var title: String? var coordinate: CLLocationCoordinate2D var username: String var post: PostModel var subtitle: Strin
final class PostAnnotation: NSObject, MKAnnotation {
var title: String?
var coordinate: CLLocationCoordinate2D
var username: String
var post: PostModel
var subtitle: String?
init(address: PostPlaceMark) {
self.title = address.title
self.coordinate = address.coordinate
self.username = address.username
self.post = address.post
self.subtitle = address.subTitle
}
}
我点击按钮加载更多数据,出于测试目的,我的数据池非常小,大约有7-10个元素。但是,每当我获取/刷新数据时,总是会得到前一组注释的副本
例如,当我的MapView首次加载我有一批注释时,点击我的刷新按钮我有一批注释1和一批注释2,但也有一批注释1的副本。再次点击refresh我有一批注释1 x 3,一批注释2 x 2,并且只有一个属于第三批注释的所有数据的实例
我已设法找出问题所在,但我有两个极端:
- 一个是我不断得到重复的注释
- 前一批的两个 除去
private static func annotationsByDistributingAnnotationsContestingACoordinate(annotations: [PostAnnotation], constructNewAnnotationWithClosure ctor: annotationRelocator) -> [PostAnnotation] {
var newAnnotations = [PostAnnotation]()
let contestedCoordinates = annotations.map{ $0.coordinate }
let newCoordinates = coordinatesByDistributingCoordinates(coordinates: contestedCoordinates)
newAnnotations.removeAll()
for (i, annotation) in annotations.enumerated() {
let newCoordinate = newCoordinates[i]
let newPost = annotation.post
let newAnnotation = ctor(annotation, newCoordinate, newPost)
print(newAnnotation.post.location)
newAnnotations.forEach { (naac) in
annotations.forEach { (element) in
if newAnnotations.contains(where: {$0.post.postID == naac.post.postID}) {
let index = newAnnotations.firstIndex{$0.post.postID == naac.post.postID}
// newAnnotations.remove(at: index!)
print("removed")
// newAnnotations.removeAll(where: {$0.post.postID == naac.post.postID})
}
}
}
newAnnotations.append(newAnnotation)
}
let withoutDuplicates = Array(Set(newAnnotations))
return withoutDuplicates
}
我可以检测元素是否已经在数组中,但是,如果删除它,即使是第一个索引也会导致注释完全丢失
这是我添加/更新注释的方式,以防您怀疑:
private func updateAnnotations(from mapView: MKMapView) {
let annotations = self.address.map(PostAnnotation.init)
let newAnnotations = ContestedAnnotationTool.annotationsByDistributingAnnotations(annotations: annotations) {
(oldAnn: MKAnnotation, newCoordinate:CLLocationCoordinate2D, post: PostModel) -> (PostAnnotation) in
PostAnnotation(address: PostPlaceMark.init(post: post, coordinate: newCoordinate, title: "\(post.manufacturer) \(post.model)", username: post.username, subTitle: "£\(post.price)"))
}
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(newAnnotations)
}
newAnnotations
是否仅打印新批注?还是复制品?@SanzioAngeli发现在我的数组中是复制品。因此,在附加新实例之前,我只需删除数组中的所有元素。