10

出于某种原因,当我的按钮被禁用时,文本颜色变为白色。我希望它保持黑色 - 我该怎么做?

4

6 回答 6

27

您可以继承 NSButtonCell 并覆盖一个方法:

- (NSRect)drawTitle:(NSAttributedString *)title withFrame:(NSRect)frame inView:(NSView *)controlView
{
    if (![self isEnabled]) {
        return [super drawTitle:[self attributedTitle] withFrame:frame inView:controlView];
    }

    return [super drawTitle:title withFrame:frame inView:controlView];
}

这样,当按钮被禁用时,文本将与启用按钮时的文本颜色相同。

于 2012-05-17T08:37:13.927 回答
7

也看看这个

[btnInfo.cell setImageDimsWhenDisabled:NO];
于 2013-05-24T13:52:13.753 回答
2

您可以覆盖 NSButtonCell 中的私有方法:

- (BOOL)_textDimsWhenDisabled {
    return NO;
}

- (BOOL)_shouldDrawTextWithDisabledAppearance {
    return NO;
}

我为一个公共方法填充了一个雷达:rdar://19218619

于 2014-12-11T12:58:23.843 回答
1

swift 4的更新:

  override func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect {

    if !self.isEnabled {
        return super.drawTitle(self.attributedTitle, withFrame: frame, in: controlView)
    }

    return super.drawTitle(title, withFrame: frame, in: controlView)
    }

这将使文本属性与启用按钮时相同。

于 2018-02-16T06:02:17.183 回答
1

在 Mojave 中,任何对 draw 方法的覆盖都使得在突出显示时无法更改 NSbutton 的 backgroundColor。所以我宁愿推荐使用

- (BOOL)_shouldDrawTextWithDisabledAppearance

以此目的。如果您使用的是 Swift 4,我会在 Bridging 标头中执行以下操作:

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

在 NSButtonCell 的子类中:

override func _shouldDrawTextWithDisabledAppearance() -> Bool {
    return false
}
于 2018-12-11T11:34:42.233 回答
-6

您可以为按钮的不同状态设置文本、图像、颜色、字体等:正常、突出显示、禁用等。

您可以在 Interface Builder 中通过使用下拉列表更改状态来执行此操作。

于 2011-06-16T12:24:39.007 回答