How do I make my MKAnnotationView scale as the user zooms in and out

I would like to make my MKAnnotation view scale as the user zooms in and out of the map similar to how the MKMarkerAnnotation currently behaves. When the user scrolls in and out of the map my custom annotation stays the same size instead of getting smaller when the user zooms out and larger when the user zooms in.


Below is the current implementation I have for my viewFor annotation: MKAnnotation method.



func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation{
            return nil
        }else if let cluster = annotation as? MKClusterAnnotation{
            let view = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier, for: cluster) as? MKMarkerAnnotationView
        
            view?.annotation = cluster
            view?.markerTintColor = UIColor.green

            return view
        }
        else if let marker = annotation as? ReusableAnnotation{
            let view = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier, for: marker)
            view.annotation = marker
            view.clusteringIdentifier = "cluster"
         
            view.canShowCallout = true
         
            // image property also holds a set size when set
         //   view.image =  imageLiteral(resourceName: "apolloRocket").resizeImage(150, opaque: false) // #imageLiteral(resourceName: "apolloRocket")

               //Sizes view to 150 by 150 square but when user zooms in and out the view stays the same size how can I resize it according to the zoom
              let subView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
              subView.backgroundColor = UIColor.red
              view.addSubview(subView)
         
            view.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
            return view
        }else{
            return nil
        }
    }

Replies

I did it like this:

(1) in mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) add your MKAnnotationViews to an array if doesn't exist in array.

(2) in mapViewDidChangeVisibleRegion(_ mapView: MKMapView) loop over the array and adjust as needed based on scale calculated from the mapView region.