JTApps JTApps - 5 months ago 37
iOS Question

UIView Hide/Show animate

My simple goal is to fade animate hiding and showing functions.

Button.hidden = YES;

Simple enough. However, is it possible to have it fade out rather than just disappearing? It looks rather unprofessional that way.


In iOS 4 and later, there's a way to do this just using the UIView transition method without needing to import QuartzCore. You can just say:

[UIView transitionWithView:button
                     button.hidden = YES;

Previous Solution

Michail's solution will work, but it's not actually the best approach.

The problem with alpha fading is that sometimes the different overlapping view layers look weird as they fade out. There are some other alternatives using Core Animation. First include the QuartzCore framework in your app and add #import <QuartzCore/QuartzCore.h> to your header. Now you can do one of the following:

1) set button.layer.shouldRasterize = YES; and then use the alpha animation code that Michail provided in his answer. This will prevent the layers from blending weirdly, but has a slight performance penalty, and can make the button look blurry if it's not aligned exactly on a pixel boundary.


2) Use the following code to animate the fade instead:

CATransition *animation = [CATransition animation];
animation.type = kCATransitionFade;
animation.duration = 0.4;
[button.layer addAnimation:animation forKey:nil];

button.hidden = YES;

The nice thing about this approach is you can crossfade any property of the button even if they aren't animatable (e.g. the text or image of the button), just set up the transition and then set your properties immediately afterwards.