开发者

Manually fade in a newly added subview?

开发者 https://www.devze.com 2022-12-30 06:17 出处:网络
I want a view to fade in when being added to the stack via [self.view addSubview:someSecondaryViewController.view];

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 开发者_Go百科(and out)?


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.


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];}];


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()
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号