2013-06-24 112 views
0

我試圖在更改自定義屬性時觸發CALayer的動畫。當我改變我的圓的半徑時,我希望圖層自動觸發它的動畫。在Objective-C中,通過將@dynamic屬性設置爲屬性並覆蓋actionForKey:方法,可以設置動畫(like in this example)。更改自定義屬性時動畫CALayer

public class MyCircle : CALayer 
{ 
    [Export ("radius")] 
    public float Radius { get; set; } 

    public MyCircle() 
    { 
     Radius = 200; 
     SetNeedsDisplay(); 
    } 

    [Export ("initWithLayer:")] 
    public MyCircle (CALayer other) : base (other) 
    { } 

    public override void Clone (CALayer other) 
    { 
     base.Clone (other); 
     MyCircle o = other as MyCircle; 
     Radius = o.Radius; 
    } 

    public CABasicAnimation MakeAnimationForKey (String key) 
    { 
     CABasicAnimation animation = CABasicAnimation.FromKeyPath (key); 
     animation.From = PresentationLayer.ValueForKey (new NSString (key)); 
     animation.Duration = 1; 
     return animation; 
    } 

    [Export ("actionForKey:")] 
    public override NSObject ActionForKey (string key) 
    { 
     switch (key.ToString()) 
     { 
      case "radius": 
       return MakeAnimationForKey (key); 
      default: 
       return base.ActionForKey (key); 
     } 
    } 

    [Export ("needsDisplayForKey:")] 
    static bool NeedsDisplayForKey (NSString key) 
    { 
     switch (key.ToString()) 
     { 
      case "radius": 
       return true; 
      default: 
       return CALayer.NeedsDisplayForKey (key); 
     } 
    } 

    public override void DrawInContext (CGContext ctx) 
    { 
     // draw circle based in radius 
    } 
} 

然而,在我的C#/ MonoTouch的代碼, 「半徑」 是從來沒有當值改變發送到ActionForKey。在上一個問題(Animate a custom property using CoreAnimation in Monotouch?)中,答案和提供的示例代碼基於手動調用的自定義屬性動畫(我不需要)。

Monotouch是否支持我所期望的行爲?我究竟做錯了什麼?

+0

究竟你是什麼意思「該自定義屬性動畫被手動調用「爲另一個答案中的示例代碼? –

+0

在GitHub上的示例代碼中,您可以在AppDelegate/FinishedLaunching中明確設置所有動畫。但是在我鏈接的Objective-C代碼中,當CALayer子類中的屬性發生更改時,將調用ActionForKey。後者是一個整潔的,因爲CALayer子類本身負責轉換(而不是調用者),更通用,減少代碼重複。 – frogge

回答

0

你錯過了在你的代碼構造函數:

[Export ("initWithLayer:")] 
public MyCircle (CALayer other) 
    : base (other) 
{ 
} 

我不知道它會解決您的問題,但它是值得一試:)

+0

我補充說,沒有成功(根據你對這個問題的回答:http://stackoverflow.com/questions/9579532/calayer-initwithlayer-bound-to-default-constructor-by-mistake-can-i-覆蓋-t) – frogge

+0

嗯,我看不出爲什麼它不工作。你能創建一個我可以嘗試的完整測試項目嗎? –

+0

https://github.com/frogge/sandbox/tree/master/MyCircle ActionForKey永遠不會被調用「radius」(它會生成動畫)。 – frogge