我尝试更改占位符文字颜色。此代码不起作用:
let color = NSColor.redColor()
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: "My placeholder", attributes: attrs)
myTextField.placeholderAttributedString = placeHolderStr
我收到错误-[NSTextField setPlaceholderAttributedString:]: unrecognized selector sent to instance
。任何想法,我如何改变占位符的颜色?
更新: 这有效:
(myTextField.cell() as NSTextFieldCell).placeholderAttributedString = placeHolderStr
更新2: 嗯,它会改变颜色,但如果文本字段获得焦点,占位符字体大小会变得更小,非常奇怪。
答案 0 :(得分:3)
以下是Swift 3.0中的一个工作示例。
let color = NSColor.red
let font = NSFont.systemFont(ofSize: 14)
let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
let placeHolderStr = NSAttributedString(string: "My placeholder", attributes: attrs)
(cell.textField.cell as! NSTextFieldCell).placeholderAttributedString = placeHolderStr
通过为NSAttributedString设置显式字体,原始问题中引用的占位符字体大小调整是固定的。
答案 1 :(得分:1)
您应该在NSTextFieldCell
而不是NSTextField
中设置占位符文字。
myTextField.cell.placeholderAttributedString = placeHolderStr
答案 2 :(得分:0)
您应该保留当前字体和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
}
}