Aaron
Aaron

Reputation: 6714

Cannot set text color of attributed placeholder in subclassed UITextField

Here's a dumbed-down version of my UITextField subclass:

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?

Upvotes: 0

Views: 324

Answers (1)

rmaddy
rmaddy

Reputation: 318954

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.

Upvotes: 1

Related Questions