2013-05-01 75 views
2

我在MonoMac中工作,並試圖在按鈕單擊時動態控制動態控件的寬度和高度約束。閱讀以下頁面後,我假設我必須使用我的約束的Animator代理。但是,以下代碼似乎無法完成工作。MonoMac上的NSLayoutConstraint動畫

NSLayoutConstraint.constant ignoring animation http://cocoa-mono.org/archives/235/using-animator-with-frameorigin/

代碼:

// makes sure we animate from 0 to calculated width 
double newWidth = ... 
widthConstraint.Constant = 0; 

var animation = new NSAnimation() { Duration = 0.5, AnimationCurve = NSAnimationCurve.EaseInOut }; 
widthConstraint.Animations = new NSDictionary("constant", animation); 
((NSLayoutConstraint)widthConstraint.Animator).Constant = newWidth; 

這樣做的結果是在控制具有newWidth的寬度,但它不顯示動畫 - 它立即改變。

回答

0

原來我使用錯誤類型的動畫。以下代碼有效:

// makes sure we animate from 0 to calculated width 
float newWidth, newHeight = ... 
widthConstraint.Constant = 0; 
heightConstraint.Constant = 30; 

var widthAnimation = new CABasicAnimation(); 
widthAnimation .TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); 
widthAnimation .Duration = 0.25; 

var heightAnimation = new CABasicAnimation(); 
widthAnimation .TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); 
widthAnimation .Duration = 0.25; 

widthConstraint.Animations = new NSDictionary("constant", widthAnimation); 
heightConstraint.Animations = new NSDictionary("constant", heightAnimation); 

NSAnimationContext.BeginGrouping(); 
NSAnimationContext.CurrentContext.Duration = widthAnimation.Duration; 
NSAnimationContext.CurrentContext.CompletionHandler = new NSAction(() => ((NSLayoutConstraint)heightConstraint.Animator).Constant = newHeight); 
((NSLayoutConstraint)widthConstraint.Animator).Constant = newWidth; 
NSAnimationContext.EndGrouping(); 

這會運行寬度動畫,然後是高度動畫。

1

您必須實際'運行'動畫。這樣做:

float newWidth = 300; 
NSAnimationContext.RunAnimation((ctx) => { 
    ctx.Duration = 0.5; 
    ctx.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); 
    ((NSLayoutConstraint)widthConstraint.Animator).Constant = newWidth; 
},() => { 
    Console.WriteLine("Animation Complete"); 
});