如何通过Interface Builder设置NSButton的文本颜色?

问题描述 投票:4回答:4

有关如何以编程方式设置文本颜色的几个问题。这一切都很好,但也必须通过Interface Builder来实现。

“显示字体”框用于更改按钮文本的大小,但Xcode忽略使用窗口小部件进行的任何颜色更改,而NSButton的属性检查器没有颜色选择器...

xcode interface-builder nsbutton
4个回答
3
投票

我不知道为什么NSButton还缺少这个。但这是Swift 4中的替换类:

import Cocoa

class TextButton: NSButton {
    @IBInspectable open var textColor: NSColor = NSColor.black
    @IBInspectable open var textSize: CGFloat = 10

    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.alignment = alignment

        let attributes: [NSAttributedStringKey : Any] = [.foregroundColor: textColor, .font: NSFont.systemFont(ofSize: textSize), .paragraphStyle: titleParagraphStyle]
        self.attributedTitle = NSMutableAttributedString(string: self.title, attributes: attributes)
    }
}

enter image description here

enter image description here


2
投票

尝试这个解决方案,我希望你会得到:)

NSFont *txtFont = button.font;
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:button.alignment];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSColor whiteColor], NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName, txtFont, NSFontAttributeName, nil];
NSAttributedString *attrString = [[NSAttributedString alloc]
                                      initWithString:button.title attributes:attrsDictionary];
[button setAttributedTitle:attrString];

0
投票

如果您喜欢“投入扩展并查看是否坚持”方法,您也可以将此扩展添加到您的代码中。

extension NSButton {

  @IBInspectable open var textColor: NSColor? {
    get {
      return self.attributedTitle.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor
    }
    set {
      var attributes = self.attributedTitle.attributes(at: 0, effectiveRange: nil)
      attributes[.foregroundColor] = newValue ?? NSColor.black
      self.attributedTitle = NSMutableAttributedString(string: self.title,
                                                       attributes: attributes)
    }
  }
}

-3
投票

编辑:误读问题。以下是如何更改iOS应用程序上按钮的文本。

只是为了澄清,这不适合你吗?

  • 添加按钮
  • 单击它并转到Attributes Inspector
  • 在“文本颜色”字段中更改颜色

© www.soinside.com 2019 - 2024. All rights reserved.