且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mapbox:仅当注释在屏幕上可见时,才添加注释

更新时间:2023-02-21 19:39:49

从我的代码中可以看出,似乎您没有正确使用复用标识符.

From what I can tell from your code it seems like you're not using reuseIdentifier properly.

resueIdentifier和使视图出队的目的是永远不要创建更多实际可见的视图(或至少将其最小化)

The goal of the resueIdentifier and dequeuing views is to never have more views created that whats actually visible (or at least minimize it)

您可以使用它来获取与您已经创建的类型相同的视图,但是不再可见或不再需要它们.因此,如果您的自定义视图具有UIImageView和标签以及某些布局,则不会再次创建它,而是重用已经创建的视图.

You use it to get views of the same type that you already created, but are not visible or needed anymore. So if your custom view has an UIImageView and a label and some layouts, you won't create it again, but reuse one that was already created.

一旦获得可用的视图,就可以分配从注释更改为注释的属性,而无需创建另一个视图.

Once you get a view back that is available you assign the properties that change from annotation to annotation without creating another view.

这意味着您下载了10,000或100,000个注释都没有关系,为地图创建的视图数将永远不会大于屏幕上可见的视图数.

What this means is that it doesn't matter if you downloaded 10,000 or 100,000 annotations, the number of views created for the map will never be larger than the number of views visible on the screen.

这样,您的代码应如下所示:

Saying that, your code should look something like this:

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    if annotation is MGLUserLocation && mapView.userLocation != nil {
        let view = CurrentUserAnnoView(reuseIdentifier: "userLocation")
        self.currentUserAnno = view
        return view
    }
    else if annotation is UserAnnotation{
        let anno = annotation as! UserAnnotation
        let reuseIdentifier = "myCustomAnnotationView"
        if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) {
        // set view properties for current annotation before returing
            annotationView.image = anno.image
            annotationView.name = anno.name // etc.
            return annotationView
        } else {
            let annotationView = UserAnnotationView(reuseIdentifier: reuseIdentifier, size: CGSize(width: 45, height: 45), annotation: annotation)
            annotationView.isUserInteractionEnabled = true
//          anno.view = annotationView // this is strange, not sure if it makes sense
            annotationView.image = anno.image // set annotation view properties
            annotationView.name = anno.name // etc.
            return annotationView
        }
    }
    return MGLAnnotationView(annotation: annotation, reuseIdentifier: "ShouldntBeAssigned")  //Should never happen
}