Jan Sanchez

UITextField and attributedPlaceholder

I wanted to do a custom format placeholder text in a UITextField and found out about the attributedPlaceholder property on the documentation.

Great! That should be easy.

1
2
3
4
5
6
7
NSDictionary *textAttributes =
      @{ NSFontAttributeName : [UIFont italicSystemFontOfSize:15.f] };
NSAttributedString *attributedPlaceholder =
      [[NSAttributedString alloc] initWithString:@"Placeholder"
                                      attributes:textAttributes];
// Assume we already have created UITextField *textField
[textField setAttributedPlaceholder:attributedPlaceholder];

So I ran the build and the placeholder should be italic as I wanted, right? WRONG!

Apparently, this is a bug. And if you had read until this line, please go and file a bug report to Apple so they can fix this.

Now, there are some workarounds for this problem. The one I ended up using is to subclass UITextField and override drawPlaceholderInRect:

1
2
3
4
5
6
7
- (void)drawPlaceholderInRect:(CGRect)rect {
  // Set to any color of your preference
  [[UIColor lightGrayColor] setFill];
  // We use self.font.pointSize in order to match the input text's font size
  [self.placeholder drawInRect:rect
                      withFont:[UIFont italicSystemFontOfSize:self.font.pointSize]];
}

It is possible to make this subclass more general and use NSAttributedString’s drawInRect: if attributedPlaceholder is set. But for my requirements the above snippet was enough.