Skip to content

Instantly share code, notes, and snippets.

@jamztang
Created September 2, 2011 08:25
Show Gist options
  • Save jamztang/1188171 to your computer and use it in GitHub Desktop.
Save jamztang/1188171 to your computer and use it in GitHub Desktop.
Adding fadeout effect to any -[UIViews removeFromSuperview]

Sometimes it’s not that please for a user to see an UI component disappearing suddenly. You’d then consider adding some transition effects, and here’s a little code snippet in the UIView+JTRemoveAnimated category for how you can get a fade out effect on view removal.

So from now on, you just needed to do this to fade out any UIViews

[myView removeFromSuperviewAnimated]
//
// UIView+JTRemoveAnimated.h
//
// Created by james on 9/1/11.
// http://ioscodesnippet.tumblr.com/
//
@interface UIView (JTRemoveAnimated)
- (void)removeFromSuperviewAnimated;
@end
//
// UIView+JTRemoveAnimated.m
//
// Created by james on 9/1/11.
// http://ioscodesnippet.tumblr.com/
//
#import <QuartzCore/QuartzCore.h>
@implementation UIView (JTRemoveAnimated)
// remove static analyser warnings
#ifndef __clang_analyzer__
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if ([animationID isEqualToString:@"fadeout"]) {
// Restore the opacity
CGFloat originalOpacity = [(NSNumber *)context floatValue];
self.layer.opacity = originalOpacity;
[self removeFromSuperview];
[(NSNumber *)context release];
}
}
- (void)removeFromSuperviewAnimated {
[UIView beginAnimations:@"fadeout" context:[[NSNumber numberWithFloat:self.layer.opacity] retain]];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView setAnimationDelegate:self];
self.layer.opacity = 0;
[UIView commitAnimations];
}
#endif
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment