问题描述
我正在尝试将文本字段中的占位符设置为斜体,并且由于我的应用程序针对iOS 6.0或更高版本,因此决定使用 attributionPlaceholder
属性而不是滚动更多内容定制。代码如下:
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;
}
然而占位符的样式仍然不是斜体,而是与常规相同文字,只是调光。我缺少什么使 NSAttributedString
工作?
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.
您可以通过创建文本字段的委托并使用如下的shouldChangeCharactersinRange来完成此操作:
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;
}
这篇关于UITextField attributesPlaceholder无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!