Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide an UI Element slowly

I have a subView that I want to toggle between hidden and not hidden by a button. How do I fade in the subview and fade it out? For now it just appears immediately and disappear immediately when I toggle the button.

I am wondering what is the easiest way to do this animation. Thanks

like image 615
Codier Avatar asked Feb 24 '23 06:02

Codier


2 Answers

On iOS 4.0+ Apple recommends you use their new, block-based animation methods. Using these, the code would look something like this:

[UIView animateWithDuration:2.0
 animations:^{myView.alpha = 0.0;}];

The properties you are animating go inside the block (the ^{...} part). Blocks are sort of like functions, so you can put multiple lines of code inside of them, if you want to animate multiple properties. For example:

[UIView animateWithDuration:0.2
 animations:^{
  view.alpha = 0.0;
  view.backgroundColor = [UIColor redColor];
 }];

If you need to perform an action after the animation is complete, use the +animateWithDuration:animations:completion: method (which also uses blocks), for example:

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

For more info, check out the UIView Class Reference 'Animations' section and 'Animating Views with Blocks' section.

like image 119
Kyle Avatar answered Mar 03 '23 12:03

Kyle


This is the old pre-4.0 way:

http://objcolumnist.com/2009/07/18/simple-uiview-based-animations-on-the-iphone/

... which has the advantage of being conceptually simple and easy to implement.

float alpha = 1.0; // or 0.0 if it's already visible and you want to fade out
[UIView beginAnimations:@"" context:NULL];
[UIView setAnimationDuration:2.0]; // seconds, not ms. guess how i know?
[mySubView setAlpha:alpha];
[UIView commitAnimations];
like image 21
MusiGenesis Avatar answered Mar 03 '23 11:03

MusiGenesis