關於如何以編程方式設置文本顏色有幾個問題。這一切都很好,但也有一種方法可以通過Interface Builder來完成。如何通過Interface Builder設置NSButton的文本顏色?
「顯示字體」對話框工程改變大小按鈕文字的,但忽略的Xcode使用小部件有所做的任何顏色變化,並且屬性檢查器NSButton沒有顏色選擇器...
關於如何以編程方式設置文本顏色有幾個問題。這一切都很好,但也有一種方法可以通過Interface Builder來完成。如何通過Interface Builder設置NSButton的文本顏色?
「顯示字體」對話框工程改變大小按鈕文字的,但忽略的Xcode使用小部件有所做的任何顏色變化,並且屬性檢查器NSButton沒有顏色選擇器...
編輯:誤讀的問題。以下是您如何更改iOS應用程序中按鈕的文本。
只是爲了澄清,這不適合你?
嘗試這種解決方案,我希望如此,你會得到:)
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];
我不知道爲什麼這是從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)
}
}
這應該被接受爲答案。謝謝! – Nitesh 2017-12-05 10:05:16
還可以將此擴展添加到您的代碼,如果你喜歡「扔在擴展和看,如果它堅持'方法。
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)
}
}
}
問題是關於NSButton(對於OS X應用程序,而不是iPhone)。屬性檢查器中沒有「文本顏色」字段(至少不像Xcode 6.1.1)。 – Troy 2015-04-10 16:51:13
Woops,誤讀了問題 - 祝你好運 – twelveandoh 2015-04-10 16:55:30