Aaron Aaron - 1 year ago 74
iOS Question

Cannot set text color of attributed placeholder in subclassed UITextField

Here's a dumbed-down version of my


class MyTextField: UITextField {

override func drawPlaceholder(in rect: CGRect) {
if let placeholder = self.placeholder {
print(placeholder) // -> prints the value
let attributes = [NSForegroundColorAttributeName: UIColor.red]
self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)

In IB, the textfield is assigned to my subclass but it doesn't matter whether I put it as "Plain" or "Attributed", the font, the color, etc. I do give it an initial placeholder value but when I run the app it's just blank. Any suggestions?

Answer Source

You are overriding the drawPlaceholder method and not calling super. And your replacement code makes no attempt to actually draw the placeholder text. Therefore the placeholder will never appear.

Why don't you override the setter for the placeholder property so it sets the attributedPlaceholder as needed. Then you don't need to override drawPlaceholder and everything will work.