2015-04-03 202 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) 
    } 
    } 
} 
相關問題