NSAnimation删除按钮的背景颜色

问题描述:

我在Mac应用程序的工作。我试图做一个简单的动画,使NSButton向下移动。动画效果非常好,但是当我这样做时,我的NSButton的背景颜色由于某种原因而消失。这里是我的代码:NSAnimation删除按钮的背景颜色

// Tell the view to create a backing layer. 
additionButton.wantsLayer = YES; 

// Set the layer redraw policy. This would be better done in 
// the initialization method of a NSView subclass instead of here. 
additionButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay; 

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) { 
    context.duration = 1.0f; 
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0.0, -20.0); 
    //additionButton.frame = CGRectOffset(additionButton.frame, 0.0, -20.0); 
} completionHandler:nil]; 

按钮向下移动的动画:

enter image description here

按钮移动后向下动画:

enter image description here

更新1

只是为了说清楚,我没有在按钮中使用背景图片。我使用的是背景NSColor我在viewDidLoad方法设置像这样:

[[additionButton cell] setBackgroundColor:[NSColor colorWithRed:(100/255.0) green:(43/255.0) blue:(22/255.0) alpha:1.0]]; 
+0

的图像不显示 – 2015-04-01 05:58:15

+0

@ysaditya但我不使用图片为我NSButton的背景。我用一个简单的NSColor填充了它。 – Supertecnoboff 2015-04-01 05:59:24

+0

你正在使用哪种按钮类型(例如瞬时推入等) – 2015-04-01 06:09:17

我想这是一个错误了AppKit。有几种方法可以解决这个问题。


解决方法1:

不要使用图层。你动画按钮似乎是小,你也许能逃脱使用非层支持的动画,仍然有它看起来体面。该按钮将在动画的每个步骤中重新绘制,但会正确动画。这意味着,这实在是所有你需要做的:

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {   
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0, -20); 
} completionHandler:nil]; 

解决方法2:

设置图层上的背景色。

additionButton.wantsLayer = YES; 
additionButton.layer.backgroundColor = NSColor.redColor.CGColor; 
additionButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay; 

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {   
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0, -20); 
} completionHandler:nil]; 

解决方法3:

子类NSButtonCell,并实现-drawBezelWithFrame:inView:,绘制背景色也。请记住,包含该按钮的父视图应该是层次支持的,否则该按钮仍然会在每一步重绘。

+0

中设置属性非常感谢你!!!!!我决定采用解决方法2,因为在阅读完您的真棒网站之后,您说过后面的动画效果更加平滑。再次感谢,并感谢他们花时间查看我在Twitter上发送的问题。这个答案已经打勾并upvoted:D – Supertecnoboff 2015-04-02 05:42:38

+3

良好的交易。确保按钮具有图层背景的父级,否则动画将不像您期望的那样平滑。 – 2015-04-02 07:56:09

+0

谢谢。会做。 – Supertecnoboff 2015-04-02 16:02:54