I'm trying to make the placeholders in my textfields italic, and since my app is targeting iOS 6.0 or newer, decided to use attributedPlaceholder
property instead of rolling something more custom. The code goes as follows:
NSString *plString = @"optional";
NSAttributedString *placeholder = [[NSAttributedString alloc] initWithString:plString
attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-LightItalic" size:15]}];
for (UITextField *t in myTextfields){
t.placeholder = plString;
t.attributedPlaceholder = placeholder;
}
Yet the styling of the placeholder still is not italic, but the same as regular text, just dimmer. What am I missing to make the NSAttributedString
work?
As noted by warren, the styling currently can't be accomplished the way you're trying. A good workaround would be to set up your textfield's font attributes the way you would like your placeholder to look and then change the font of the textfield whenever the user begins typing. It will look like the placeholder and text are different fonts.
You can do this by creating a delegate of the textfield and utilizing shouldChangeCharactersinRange like this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// If there is text in the text field
if (textField.text.length + (string.length - range.length) > 0) {
// Set textfield font
textField.font = [UIFont fontWithName:@"Font" size:14];
} else {
// Set textfield placeholder font (or so it appears)
textField.font = [UIFont fontWithName:@"PlaceholderFont" size:14];
}
return YES;
}
This is almost certainly a bug. The documentation for the attributedPlaceholder
property claims that the string will be drawn using a gray color regardless of the foreground color attribute, but this is not the case: you can set both the foreground and background colors. Unfortunately, the font attribute appears to get stripped out and reverted to the system font.
As a workaround, I recommend overriding drawPlaceholderInRect:
and drawing the placeholder yourself. Additionally, you should file a Radar on this and include a minimal sample project that demonstrates the bug.
I just stumbled upon this issue myself. Apparently, the placeholder will take whatever font the textfield is being assigned with. Just set the textfield's font and you are good.
For everything else, like the colour of the placeholder, I'd still go back to attributedPlaceholder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With