16

I want a view to fade in when being added to the stack via

[self.view addSubview:someSecondaryViewController.view];

How do I animate this call so that the view fades in (and out)?

Moshe
  • 57,511
  • 78
  • 272
  • 425

3 Answers3

29

Set the alpha to zero before animating, then animate the alpha to one.

[fadingView setAlpha:0.0];
[containerView addSubview:fadingView];
[UIView beginAnimations:nil context:nil];
[fadingView setAlpha:1.0];
[UIView commitAnimations];

Before removing the view, just animate the alpha back to zero.

BTW, the view hierarchy is more of a tree than a stack.

Edit:

If you have no other cleanup after the animation ends when fading out the view, then use:

[UIView setAnimationDelegate:fadingView];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

If you are already setting a didStopSelector then call removeFromSuperview there.

drawnonward
  • 53,459
  • 16
  • 107
  • 112
  • What happens when my fade ends at 0.0? It seems to be removing my subview. I want this to happen, but should I worry about memory management? If I explicitly add code to remove the subview, the animation doesn't show. – Moshe May 17 '10 at 00:59
  • 1
    Use the `+setAnimationDidStopSelector` method to remove the `fadingView` from the superview. – Alex Reynolds May 17 '10 at 03:54
21

You could also use blocks to remove a view from its super view after it has finished the fade out animation:

[UIView animateWithDuration:0.2
                 animations:^{viewOut.alpha = 0.0;}
                 completion:^(BOOL finished){[viewOut removeFromSuperview];}];
WebSeed
  • 1,687
  • 1
  • 15
  • 19
1

And in Swift …

In

someSecondaryViewController.view.alpha = 0.0
self.view.addSubview(someSecondaryViewController.view)
UIView.animate(withDuration: 0.2, animations: { self.someSecondaryViewController.view.alpha = 1.0 })

Out

UIView.animate(withDuration: 0.2, animations: { self.someSecondaryViewController.view.alpha = 0.0 }) { (done: Bool) in
    self.someSecondaryViewController.view.removeFromSuperview()
}
Karen Hovhannisyan
  • 1,140
  • 2
  • 21
  • 31
dumbledad
  • 16,305
  • 23
  • 120
  • 273