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];
和类比动画代理支持要老得多NSAnimation,NSViewAnimation我强烈建议您尽可能远离它们。支持NSAnimatablePropertyContainer协议比管理所有委托的东西要简单得多。NSAnimationLion 对自定义计时功能和完成处理程序的支持意味着真的没有必要再这样做了。
对于标准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:方法以找出动画的当前值。