MonoMac上的NSLayoutConstraint动画

时间:2013-05-01 16:23:28

标签: core-animation monomac nslayoutconstraint

我正在使用MonoMac,并尝试在按钮单击时动态设置控件的宽度和高度约束。阅读以下页面后,我假设我必须使用约束的Animator代理。但是,以下代码似乎无法完成工作。

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但没有动画 - 它会立即更改。

2 个答案:

答案 0 :(得分: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"); 
});

答案 1 :(得分: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();

这会运行宽度动画,然后是高度动画。