Manually fade in a newly added subview?
Asked Answered
I

3

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)?

Inundate answered 17/5, 2010 at 0:2 Comment(0)
M
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.

Montero answered 17/5, 2010 at 0:45 Comment(2)
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.Inundate
Use the +setAnimationDidStopSelector method to remove the fadingView from the superview.Photoluminescence
A
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];}];
Ardellardella answered 17/3, 2011 at 10:13 Comment(0)
A
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()
}
Averroes answered 16/6, 2016 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.