Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...