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
. 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.
By explicitly defining the font of the NSAttributedString, the placeholder font resizing referred to in the original question is fixed.
The following is a working example in 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.
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
You should set the placeholder text in NSTextFieldCell
and not NSTextField
.
myTextField.cell.placeholderAttributedString = placeHolderStr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With