【问题标题】:Is there a way to prevent text from becoming gray when I disable a button?当我禁用按钮时,有没有办法防止文本变灰?
【发布时间】:2017-03-11 18:27:02
【问题描述】:

当我将按钮设置为禁用时,文本变为灰色(之前为黑色)。 在我的窗口中,结果是禁用按钮时文本不可读。

我翻遍了 NSButton/NSButtonCell/NSCell/NSControl 的文档,但没有找到任何方法来保持文本为黑色。你知道我该怎么做吗?

【问题讨论】:

  • 您能否覆盖按钮的属性而不是禁用它 - 但可能会禁用交互,或者只是更改按钮的颜色/边框以使其保留您的文本颜色?只是想知道你是否尝试过这个修复,不过我知道你在说什么。
  • mmmm.. 我想我可以将图像/备用图像设置为相同的“禁用”皮肤,这样用户就会明白这是禁用的。但这会使代码非常难看 - 如果按钮被禁用,我必须检查每个操作函数
  • 在 iOS 中,我可以这样做: myButton.userInteractionDisabled = YES 然后设置 alpha 使其看起来像被禁用。我想你可以用你的 NSButton 做类似的事情。只是为了确认一下,您只是将 enabled 属性设置为 NO,这就是您的文本颜色问题的来源?
  • 是的,我将启用属性设置为知道。我试图找到一种方法来像在 iOS 中那样禁用用户交互,但没有运气。
  • 解决方案stackoverflow.com/a/10632311/594211 也解决了这个问题。

标签: objective-c cocoa macos


【解决方案1】:

您可以为 IB 中的每个状态设置按钮属性(字体、颜色)。那么将禁用状态的文本颜色设置为黑色有帮助吗?

【讨论】:

  • 我在 IB 中没有看到这样的选项。我使用带有内置 IB 的 xcode 4
  • 可可不是可可粉吗?
【解决方案2】:

子类 NSButtonCell 并将其分配给 IB 中的按钮 CELL (不是 BUTTON 直接 -> 更深一层)。在子类中实现以下并根据需要修改大小、字体和颜色:

- (NSAttributedString*)attributedTitleForString:(NSString*)string
{
    // Colors
    NSColor *disabledColor = [NSColor grayColor];
    NSColor *enabledColor = [NSColor redColor];

    // Font
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSLeftTextAlignment];
    NSFont *font = [NSFont systemFontOfSize:11];

    // Enabled
    NSDictionary *enabledAttrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                        enabledColor, NSForegroundColorAttributeName,
                                        style, NSParagraphStyleAttributeName,
                                        font, NSFontAttributeName,
                                        nil];
    NSAttributedString* enabledTitle = [[NSAttributedString alloc]initWithString:string attributes:enabledAttrsDictionary];

    // Disabled
    NSDictionary *disabledAttrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                         disabledColor, NSForegroundColorAttributeName,
                                         style, NSParagraphStyleAttributeName,
                                         font, NSFontAttributeName, nil];

    NSAttributedString* disabledTitle = [[NSAttributedString alloc]initWithString:string attributes:disabledAttrsDictionary];

    if (![self isEnabled])
        return disabledTitle;
    else
        return enabledTitle;
}

编辑:仅当 setWantsLayers 为 false 时才有效

【讨论】:

    【解决方案3】:

    在 cocoa touch 上有一个 API:

    [myButton setTextColor:[UIColor blackColor] forState:UIControlStateDisabled];

    可可我不知道。

    【讨论】:

    • 这解决了 Cocoa Touch 的问题,但不是 Cocoa,这是提问者所问的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 2011-03-20
    • 2018-11-28
    • 2010-09-28
    • 2011-08-01
    • 2012-10-17
    相关资源
    最近更新 更多