2013-05-01 59 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"); 
});