NSAnimation
對於同時動畫多個對象及其屬性並不是真正的最佳選擇。
相反,您應該使您的意見符合NSAnimatablePropertyContainer
協議。
然後,您可以設置多個自定義屬性爲動畫(除由NSView
已經支持的屬性),然後你可以簡單地使用你的意見animator
代理動畫屬性:
yourObject.animator.propertyName = finalPropertyValue;
除了從製作動畫非常簡單,它也可以讓你的動畫多個對象同時使用NSAnimationContext
:
[NSAnimationContext beginGrouping];
firstObject.animator.propertyName = finalPropertyValue1;
secondObject.animator.propertyName = finalPropertyValue2;
[NSAnimationContext endGrouping];
您還可以設置時間,並提供一個完成處理BLO CK:
[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
協議是多比管理所有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];
}
}
我創建了一個簡單的sample project,演示瞭如何使用NSAnimatablePropertyContainer
協議同時動畫化視圖的多個屬性。
所有視圖需要做成功更新是確保在任何動畫的屬性被修改setNeedsDisplay:YES
被調用。然後,您可以在drawRect:
方法中獲取這些屬性的值,並根據這些值更新動畫。
如果你想要一個簡單的進度值是類似的事情NSAnimation
的工作方式,你可以定義你的視圖progress
屬性,然後做這樣的事情:
yourView.progress = 0;
[yourView.animator setProgress:1.0];
然後,您可以訪問self.progress
在你的drawRect:
方法中找出動畫的當前值。
第二部動畫在哪裏?什麼方法不起作用? – 2012-04-15 23:01:05