NSAnimation
并不是同时为多个对象及其属性设置动画的最佳选择。
相反,你应该使你的观点符合NSAnimatablePropertyContainer协议。
然后,您可以将多个自定义属性设置为可动画(除了已经支持的属性之外)NSView
),然后你可以简单地使用你的观点'animator
代理来动画属性:
yourObject.animator.propertyName = finalPropertyValue;
除了使动画变得非常简单之外,它还允许您使用NSAnimationContext
:
[NSAnimationContext beginGrouping];
firstObject.animator.propertyName = finalPropertyValue1;
secondObject.animator.propertyName = finalPropertyValue2;
[NSAnimationContext endGrouping];
您还可以设置持续时间并提供完成处理程序块:
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.5];
[[NSAnimationContext currentContext] setCompletionHandler:^{
NSLog(@"animation finished");
}];
firstObject.animator.propertyName = finalPropertyValue1;
secondObject.animator.propertyName = finalPropertyValue2;
[NSAnimationContext endGrouping];
The NSAnimation
and NSViewAnimation
类比动画师代理支持要老得多,我强烈建议您尽可能远离它们。支持NSAnimatablePropertyContainer
协议是much比管理所有的更简单NSAnimation
委托的事情。 Lion 对自定义计时函数和完成处理程序的支持意味着实际上不再需要这样做。
对于一个标准NSView
对象,如果你想为视图中的属性添加动画支持,你只需要重写+defaultAnimationForKey:
视图中的方法并返回属性的动画:
//declare the default animations for any keys we want to animate
+ (id)defaultAnimationForKey:(NSString *)key
{
//in this case, we want to add animation for our x and y keys
if ([key isEqualToString:@"x"] || [key isEqualToString:@"y"]) {
return [CABasicAnimation animation];
} else {
// Defer to super's implementation for any keys we don't specifically handle.
return [super defaultAnimationForKey:key];
}
}
我创建了一个简单的示例项目展示了如何使用同时为视图的多个属性设置动画NSAnimatablePropertyContainer
协议。
要成功更新您的视图所需要做的就是确保setNeedsDisplay:YES
当任何可设置动画的属性被修改时调用。然后您可以在您的drawRect:
方法并根据这些值更新动画。
如果您想要一个类似于事物工作方式的简单进度值NSAnimation
,你可以定义一个progress
属性在你的视图中,然后执行如下操作:
yourView.progress = 0;
[yourView.animator setProgress:1.0];
然后您可以访问self.progress
在你的drawRect:
方法来找出动画的当前值。