在iPhone上的UIView中很容易实现FadeIn动画,只需要在如下代码中对alpha进行操作。
theView.alpha = 0.0f;
[UIView beginAnimations:@"fadeIn" context:nil];
[UIView setAnimationDuration:1.0];
theView.alpha = 1.0f;
[UIView commitAnimations];
但是Mac(Snow leopard)上的NSView中,对alpha值做类似的处理是没有任何淡入淡出效果的。下面的代码无效。就算是layer backed,依然无效。
[theView setAlphaValue:0.0f];
[[theView animator] setAlphaValue:0.8f];
搜索了很久,发现addSubView和removeFromSuperview是有淡入淡出效果。例如:
[[theSuperview animator] addSubview:theView];
但通过下面的代码无法改变持续时间:
CABasicAnimation *animation = [CABasicAnimation animation];
animation.duration = 3.0f;
[theSuperview setAnimations:[NSDictionary dictionaryWithObjectsAndKeys:animation, @"FadeIn", nil]];
[[theSuperview animator] addSubview:theView];
经过摸索,终于找到了比较完美的解决方法。
FadeIn淡入动画:
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:2.0];
[[theSuperview animator] addSubview:theView];
[NSAnimationContext endGrouping];
FadeOut淡出动画:
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:2.0];
[[theView animator] removeFromSuperview];
[NSAnimationContext endGrouping];