Tips10-修改UITextField的placeholder字体

我经常使用的修改UITextField的placeholder字体方法有两种:

KVC

1
2
3
yourTextField.placeholder = @"username is here";
[yourTextField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[yourTextField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

设置AttributedPlaceholder

1
2
NSDictionary *attributed = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor redColor]};
youTextFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"username is in here!" attributes:attributed];

我个人推荐使用Attributed的方式来设置,因为KVC不知道什么时候会失效,而且适用范围比较小。
有时候,当字体过小的时候,placeholder的字体会显示不是垂直居中的,这需要用到NSParagraphStyle,而用KVC是没法解决的。

我的解决办法是:

1
2
3
NSMutableParagraphStyle *style = [yourTextField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
style.minimumLineHeight = yourTextField.font.lineHeight - (yourTextField.font.lineHeight - [UIFont systemFontOfSize:14.0].lineHeight) / 2.0;
yourTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"username is in here!" attributes:@{NSForegroundColorAttributeName: [UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSParagraphStyleAttributeName: style}];