macos - NSAnimation 删除按钮背景颜色

标签 macos cocoa nsbutton nsanimationcontext nsanimation

我正在开发 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];

按钮向下移动动画:

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]];

最佳答案

我认为这是一个 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/

相关文章:

c++ - Apple Mach -O(ID)链接器错误,ncurses

c - Mac 上架构 x86_64 错误的 undefined symbol

cocoa - OpenGL 中不需要的透明度

cocoa 用于控制事件 :WHATGOESHERE

macos - Applescript 问题 : "Not Allowed Assistive Access. (-1719)"

macos - Mac OS X | Bash .bash_profile 未更新 PS1

objective-c - beginSheet modalForwindow : nil position?

cocoa - 在 NSPersistentDocument 中哪里可以获取托管对象上下文?

cocoa - 命名多个 NSButton

cocoa - 如何防止 NSButton 在禁用时注册按下操作?