淡入淡出动画 [英] Fade In Fade Out Animation
问题描述
有些代码我需要一段时间才能解决。
Here is some code I struggle with for a while.
如果您开始淡入淡出动画,标签文本就会淡入。
如果我开始
If you start the fade in animation, the label text fades in. If I start the fade out animation the the label text fades out.
当我启动 startFade
方法时,只有淡出是如图所示。在启动 fadeOut
方法之前,我应该如何等待 fadeIn
方法可视地完成。
When I start the startFade
method, only fade out is shown. How can I wait for the fadeIn
method to finish visually before starting the fadeOut
method.
-(IBAction)startFade:(id)sender{
[self fadeIn];
[self fadeOut];
}
-(IBAction)fadeIn:(id)sender{
[self fadeIn];
}
-(IBAction)fadeOut:(id)sender{
[self fadeOut];
}
-(void) fadeIn{
[_label setAlpha:0];
[UILabel beginAnimations:NULL context:nil];
[UILabel setAnimationDuration:2.0];
[_label setAlpha:1];
[UILabel commitAnimations];
}
-(void) fadeOut{
[UILabel beginAnimations:NULL context:nil];
[UILabel setAnimationDuration:2.0];
[_label setAlpha:0];
[UILabel commitAnimations];
}
推荐答案
调用 fadeIn
和 fadeOut
方法像您正在做的那样背靠背,代码会立即运行,因此您只会看到动画从最后一个方法调用。基于UIView块的动画提供了完成处理程序,这似乎正是您所需要的。因此您的代码可能看起来像这样:
When you call the fadeIn
and fadeOut
methods back to back like you're doing, the code is run instantaneously, so you'll only see animation from the last method called. UIView block based animation provides a completion handler, which seems to be exactly what you're looking for. So your code might looks something like this:
-(IBAction)startFade:(id)sender {
[_label setAlpha:0.0f];
//fade in
[UIView animateWithDuration:2.0f animations:^{
[_label setAlpha:1.0f];
} completion:^(BOOL finished) {
//fade out
[UIView animateWithDuration:2.0f animations:^{
[_label setAlpha:0.0f];
} completion:nil];
}];
}
Swift:
@IBAction func startFade(_ sender: AnyObject) {
label.alpha = 0.0
// fade in
UIView.animate(withDuration: 2.0, animations: {
label.alpha = 1.0
}) { (finished) in
// fade out
UIView.animate(withDuration: 2.0, animations: {
label.alpha = 0.0
})
}
}
这篇关于淡入淡出动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!