1

I have been stuck on this issue for the past day. I have created a custom MKAnnotation subclass to display various custom pins on an MKMapView. I recursively call a function that keeps animating these pins around the map. My goal is to stop all of these animations in place when the user taps on a button. I have tried

self.view.layer.removeAllAnimations()

and

self.map.layer.removeAllAnimations()

and other hacky solutions, but none seem to work.

Below is the code that creates the animation/pin movement

func animate(duration:Double, newLocation:CLLocationCoordinate2D){
    UIView.animate(withDuration: duration, animations: {
        self.coordinate = newLocation
    }) { (done) in
        self.finished_segment()
    }
} 

Any suggestions are much appreciated.

  • You might be able to do this using iOS 10's `UIViewPropertyAnimator`. To see if this would work, I would setup an animator for each `UIView` and then call `.startAnimation()` on each animator to start the animation. To stop the animation of a particular `UIView` call the `.stopAnimation(true)` on the appropriate animator. – Robotic Cat May 20 '17 at 19:37
  • Possible duplicate of [How to cancel UIView block-based animation?](http://stackoverflow.com/questions/9569943/how-to-cancel-uiview-block-based-animation) – Robotic Cat May 20 '17 at 19:37

1 Answers1

1

For anyone stuck on this issue. The problem was that I had to remove the animation from the MKAnnotationView associated with the annotation. I basically created a member variable in the custom class that I set in the mapView annotation delegate method as seen below.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "annotationView") ?? MKAnnotationView()
    if let a = annotation as? Alien{
        annotationView.image = a.image
        a.annotationView = annotationView
    }

    return annotationView
}

And to remove the animation from the map. Simply call

self.annotationView.layer.removeAllAnimations()