关于如何以编程方式设置文本颜色有几个问题。这一切都很好,但也有一种方法可以通过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