2015-04-03 206 views
3

关于如何以编程方式设置文本颜色有几个问题。这一切都很好,但也有一种方法可以通过Interface Builder来完成。如何通过Interface Builder设置NSButton的文本颜色?

“显示字体”对话框工程改变大小按钮文字的,但忽略的Xcode使用小部件有所做的任何颜色变化,并且属性检查器NSButton没有颜色选择器...

回答

-3

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

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

  • 添加的按钮
  • 点击它,并转到属性检查器
  • 改变颜色“文本颜色”字段

Changed button color to reddish

+1

问题是关于NSButton(对于OS X应用程序,而不是iPhone)。属性检查器中没有“文本颜色”字段(至少不像Xcode 6.1.1)。 – Troy 2015-04-10 16:51:13

+0

Woops,误读了问题 - 祝你好运 – twelveandoh 2015-04-10 16:55:30

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

“Interface builder”... – quemeful 2017-03-13 12:59:43

+0

@quemeful不,你不能设置,但你可以通过运行时设置属性是可能的。 – Gowtham 2017-03-14 09:44:27

1

我不知道为什么这是从NSButton仍然丢失。但这里是斯威夫特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

+0

这应该被接受为答案。谢谢! – Nitesh 2017-12-05 10:05:16

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) 
    } 
    } 
} 
相关问题