我尝试更改占位符文本颜色。此代码不起作用:
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: 嗯,它改变了颜色,但是如果文本字段获得焦点,占位符字体大小会变小,很奇怪。
最佳答案
通过显式定义 NSAttributedString 的字体,原始问题中提到的占位符字体大小调整是固定的。
以下是 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
以下是 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
关于Cocoa NSTextField 更改占位符颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25106372/