Animating removeFromSuperview

Although approach with sending removeFromSuperview message from animation completion block works fine for most cases, sometimes there is no way to prevent a view from immediate removal from view hierarchy.

For example, MKMapView removes its subviews after it receives message removeAnnotations, and there is no "animated" alternative for this message in the API.

Nonetheless the following code allows you to do whatever you like with a visual clone of a view after it's been removed from superview or even deallocated:

UIView * snapshotView = [view snapshotViewAfterScreenUpdates:NO];
snapshotView.frame = view.frame;
[[view superview] insertSubview:snapshotView aboveSubview:view];

// Calling API function that implicitly triggers removeFromSuperview for view
[mapView removeAnnotation: annotation];

// Safely animate snapshotView and release it when animation is finished
[UIView animateWithDuration:1.0
                     snapshotView.alpha = 0.0;
                 }
                 completion:^(BOOL finished) {
                     [snapshotView removeFromSuperview];
                 }];

I think you need to do forView:self.view.superview instead, to be consistent with what you are doing when you are adding, because in this case the self.view is the child, and so you would need to do it on the parent.


If you're targeting iOS 4.0 upwards you can use animation blocks instead:

[UIView animateWithDuration:0.2
     animations:^{view.alpha = 0.0;}
     completion:^(BOOL finished){ [view removeFromSuperview]; }];

(above code comes from Apple's UIView documentation)


JosephH answer in Swift:

UIView.animateWithDuration(0.2, animations: {view.alpha = 0.0}, 
                                completion: {(value: Bool) in
                                              view.removeFromSuperview()
                                            })