UITextField attributedPlaceholder Doesn’t Work

The Problem

In my efforts to build an easier way to create forms I stumbled across and interesting bug in UIKit. Apparently the attributedPlaceholder property doesn’t work. Not only does it not display based on the attributes you set, but it also strips them out completely. This means to retain access to the attributes you set, you have to override the setter and store it before it is tainted.

The Solution

Note: Keep in mind that this fix has only been tested on iOS 6.0 and up.

To work around this bug, you have to create a subclass of UITextField and override the -setAttributedPlaceHolder to store the result in an ivar. Then you have to override the -drawPlaceholderInRect method and enumerate over the attributes and draw the text using -drawAtPoint method of NSAttributedString+NSStringDrawing (the only iOS 6 specific method). This allow support for custom attributes which can help when tweeking a design.

A Helpful Subclass

Below is a link to a subclass I wrote to work around the problem. It has support for the following…

  • Substring colors
  • Substring fonts
  • Substring baseline offset
  • Substring left offset

With these select attributes you should be able to match the placeholder text to any design.

See the code

Leave a Reply

Your email address will not be published. Required fields are marked *