Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa NSTextField change placeholder color

Tags:

swift

cocoa

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.

like image 823
Lupurus Avatar asked Aug 03 '14 15:08

Lupurus


2 Answers

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
like image 106
Victor Fagerström Avatar answered Nov 12 '22 22:11

Victor Fagerström


You should set the placeholder text in NSTextFieldCell and not NSTextField.

myTextField.cell.placeholderAttributedString = placeHolderStr
like image 24
TheAmateurProgrammer Avatar answered Nov 12 '22 22:11

TheAmateurProgrammer