Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField attributedPlaceholder has no effect

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?

like image 348
SaltyNuts Avatar asked Feb 22 '13 19:02

SaltyNuts


3 Answers

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;
}
like image 77
Mike Avatar answered Nov 18 '22 10:11

Mike


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.

like image 38
warrenm Avatar answered Nov 18 '22 10:11

warrenm


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

like image 8
XCool Avatar answered Nov 18 '22 10:11

XCool