How to animate an MKMapKit annotation removal

349 Views Asked by At

Please can someone help with a MapView question. I have a custom annotation. When the user taps the annotation, I want it to move up the screen and then disappear. As a test of the animation code (as I am new to this!), I tried the following:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    guard let pinTapped = view.annotation as? Pin else {return}
    guard let pinName = pinTapped.title else { return }
    let endFrame = CGRect(x: view.frame.origin.x, y: view.frame.origin.y - self.view.bounds.size.height, width: view.frame.size.width, height: view.frame.size.height)
    UIView.animate(withDuration: 3.0, animations: {
        view.frame = endFrame
    }) { (finished) in
        self.mapKitView.removeAnnotation(pinTapped)
    }
}

I expected the annotation to slide to the new position over 3 seconds and then disappear. What actually happen is that it immediately moves to the new position, and slides back to the original position, and then disappears. What am I doing wrong?

1

There are 1 best solutions below

0
On
extension UIView {
    func disappearAnimation(_ completion: @escaping () -> ()) {

        let opacity = CASpringAnimation(keyPath: "opacity")
        let position = CASpringAnimation(keyPath: "position")
        let group = CAAnimationGroup()

        opacity.fromValue = 1
        opacity.toValue = 0

        position.fromValue = self.center
        position.toValue = CGPoint(x: self.center.x, y: self.center.y - 300) //You can change it

        group.animations = [opacity, position]

        group.duration = 1.1 // You can change it
        group.repeatCount = 0
        group.autoreverses = false
        group.timingFunction = CAMediaTimingFunction(name: .easeOut) //You can change also timing func

        layer.add(group, forKey: nil)

        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            completion()
        }
    }
}

After you add this animation and customize as you desired,

func pinTapped(_ pin: MKAnnotationView) {

    pin.disappearAnimation {
        //Remove your view after animation is shown
    }
}

I hope this solution helped