我正在开发一个Mac应用程序。我试图做一个简单的动画,使一个NSButton向下移动。动画效果真的很好,但是当我这样做的时候,我的NSButton的背景色由于某种原因消失了。这是我的代码:
// 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];按钮向下移动动画:

按钮后,移动动画:

更新1
为了表明这一点,我没有在我的按钮中使用背景图像。我使用的是在viewDidLoad方法中设置的背景viewDidLoad,如下所示:
[[additionButton cell] setBackgroundColor:[NSColor colorWithRed:(100/255.0) green:(43/255.0) blue:(22/255.0) alpha:1.0]];发布于 2015-04-01 23:23:10
我猜想这是一个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:,在那里绘制背景色。请记住,包含该按钮的父视图应该是层支持的,否则该按钮仍将在每一步上重新绘制。
https://stackoverflow.com/questions/29383786
复制相似问题