我正在开发 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
为了明确起见,我没有在按钮中使用背景图像。我正在使用背景 NSColor,我在 viewDidLoad 方法中设置它,如下所示:
[[additionButton cell] setBackgroundColor:[NSColor colorWithRed:(100/255.0) green:(43/255.0) blue:(22/255.0) alpha:1.0]];
最佳答案
我认为这是一个 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:
,在那里绘制背景颜色。请记住,包含按钮的父 View 应该是图层支持的,否则按钮仍将在每一步中重绘。
关于macos - NSAnimation 删除按钮背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383786/