【问题标题】:NSButton disabled title color always grayNSButton 禁用标题颜色始终为灰色
【发布时间】:2018-12-11 19:33:11
【问题描述】:

我有一个自定义的 NSButton,但无论我做什么,禁用的颜色总是灰色

我尝试了所有遇到的解决方案

  • 我正在用白色前景色设置属性字符串标题(我看起来颜色属性在禁用状态下被忽略了)

  • 我确实设置了 [[self cell] setImageDimsWhenDisabled:NO];

文档状态时的事件

// When disabled, the image and text of an NSButtonCell are normally dimmed with gray.
// Radio buttons and switches use (imageDimsWhenDisabled == NO) so only their text is dimmed.
@property BOOL imageDimsWhenDisabled;

没用

我的 NSButton 使用 WantUpdateLayer YES,所以绘制方法被覆盖了,但是我不明白,标题是在哪里绘制的

【问题讨论】:

    标签: macos cocoa nsbutton


    【解决方案1】:

    在 OS X 10.9 上,当按钮文本被禁用时,我通过对绘制按钮的单元格进行子分类来更改按钮文本的颜色。

    在 Xcode 中创建一个新的NSButtonCell 子类并覆盖以下方法:

    - (NSRect)drawTitle:(NSAttributedString *)title
          withFrame:(NSRect)frame
             inView:(NSView *)controlView {
    
        NSDictionary *attributes = [title attributesAtIndex:0 effectiveRange:nil];
    
        NSColor *systemDisabled = [NSColor colorWithCatalogName:@"System" 
                                                      colorName:@"disabledControlTextColor"];
        NSColor *buttonTextColor = attributes[NSForegroundColorAttributeName];
    
        if (systemDisabled == buttonTextColor) {
            NSMutableDictionary *newAttrs = [attributes mutableCopy];
            newAttrs[NSForegroundColorAttributeName] = [NSColor orangeColor];
            title = [[NSAttributedString alloc] initWithString:title.string
                                                attributes:newAttrs];
        }
    
         return [super drawTitle:title
                  withFrame:frame
                     inView:controlView];
    
    }
    

    在 Xcode 中选择按钮,然后选择其单元格(在 Interface Builder 停靠栏中可能最容易做到这一点),现在进入 Identity Inspector 并将单元格的类设置为您的子类的类。

    【讨论】:

    • 但是当使用 WantUpdateLayer YES 时,不会调用 drawTitle
    • 我的印象是,当按钮被禁用时,您只是使用图层来影响按钮的颜色。除了影响禁用的文本颜色之外,您还使用图层做什么?当你不使用图层时,你的颜色变化工作正常吗?
    • 是的,问题出在使用 WantUpdateLayer YES 时
    【解决方案2】:

    这是因为默认的真值

    - (BOOL)_shouldDrawTextWithDisabledAppearance

    尝试更改此方法而不是 imageDimsWhenDisabled。如果您使用的是 Swift 4,我会在 Bridging 标头中执行以下操作:

    #import <AppKit/AppKit.h>
    @interface NSButtonCell (Private)
    - (BOOL)_shouldDrawTextWithDisabledAppearance;
    @end
    

    并且在 NSButtonCell 的子类中:

    override func _shouldDrawTextWithDisabledAppearance() -> Bool {
        return false
    }
    

    就是这样:灰色应该消失

    【讨论】:

    • 但那是私有 API :(
    • 是的,这就是我们在 Swift 4 中进行桥接的原因。在 Mojave 中,如果您想通过 func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView 更改突出显示的 NSButton 的颜色),如果你重写任何 NSButtonCell 的绘制方法,你将无法做到。这是您必须更改 Apple 的“灰色”禁用按钮的默认方式的唯一方法。
    猜你喜欢
    • 2020-12-26
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2020-06-19
    相关资源
    最近更新 更多