[英]Cocoa NSTextField change placeholder color
I try to change the placeholder text color. 我尝试更改占位符文本颜色。 This code doesn't work:
此代码不起作用:
let color = NSColor.redColor()
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: "My placeholder", attributes: attrs)
myTextField.placeholderAttributedString = placeHolderStr
I get the error -[NSTextField setPlaceholderAttributedString:]: unrecognized selector sent to instance
. 我收到错误
-[NSTextField setPlaceholderAttributedString:]: unrecognized selector sent to instance
。 Any ideas, how I can change the color of the placeholder? 任何想法,我怎么能改变占位符的颜色?
UPDATE: This works: 更新:这有效:
(myTextField.cell() as NSTextFieldCell).placeholderAttributedString = placeHolderStr
UPDATE 2: Hmm, it changes the color, but if the text field gets the focus, the placeholder font size get's smaller, very strange. 更新2:嗯,它改变颜色,但如果文本字段获得焦点,占位符字体大小变得更小,非常奇怪。
By explicitly defining the font of the NSAttributedString, the placeholder font resizing referred to in the original question is fixed. 通过显式定义NSAttributedString的字体,原始问题中引用的占位符字体大小调整是固定的。
The following is a working example in Swift 3.0. 以下是Swift 3.0中的一个工作示例。
let color = NSColor.red
let font = NSFont.systemFont(ofSize: 14)
let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
let placeholderString = NSAttributedString(string: "My placeholder", attributes: attrs)
(textField.cell as? NSTextFieldCell)?.placeholderAttributedString = placeholderString
The following is a working example in Swift 4.2. 以下是Swift 4.2中的一个工作示例。
let attrs = [NSAttributedString.Key.foregroundColor: NSColor.lightGray,
NSAttributedString.Key.font: NSFont.systemFont(ofSize: 14)]
let placeholderString = NSAttributedString(string: "My placeholder", attributes: attrs)
(taskTextField.cell as? NSTextFieldCell)?.placeholderAttributedString = placeholderString
您应该在NSTextFieldCell
而不是NSTextField
设置占位符文本。
myTextField.cell.placeholderAttributedString = placeHolderStr
You should keep current font, and current value from IB 你应该保留IB的当前字体和当前值
extension NSTextField {
func setHintTextColor (color: NSColor) {
let currentHint = placeholderString ?? ""
let placeholderAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: color,
NSAttributedString.Key.font: font!
]
let placeholderAttributedString = NSMutableAttributedString(string: currentHint, attributes: placeholderAttributes)
let paragraphStyle = NSMutableParagraphStyle()
placeholderAttributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0,length: placeholderAttributedString.length))
self.placeholderAttributedString = placeholderAttributedString
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.