UITextField属性Placeholder不起作用

我试图使我的textfields的占位符斜体,并且由于我的应用程序是针对iOS 6.0或更高版本,决定使用的attributedPlaceholder属性,而不是滚动更多的自定义。 代码如下:

 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工作?

正如沃伦所指出的那样,目前的造型不能像你所想的那样完成。 一个好的解决方法是设置您的文本字段的字体属性的方式,你希望你的占位符,然后改变文本字段的字体,每当用户开始input。 它看起来像占位符,文字是不同的字体。

您可以通过创build文本字段的委托并使用shouldChangeCharactersinRange像这样做:

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

这几乎肯定是一个错误。 attributedPlaceholder PropertyPlaceholder属性声明,string将使用灰色绘制,而不考虑前景颜色属性,但情况并非如此:您可以同时设置前景色和背景色。 不幸的是,字体属性似乎被剥离,并恢复到系统字体。

作为一种解决方法,我build议重写drawPlaceholderInRect:并自己绘制占位符。 此外,你应该在这个文件上包含一个雷达,并包含一个最小的示例项目来演示这个bug。

我自己也偶然发现了这个问题。 显然,占位符将采取任何字体的文本字段分配。 只要设置文本字段的字体,你就很好。

对于其他所有内容,比如占位符的颜色,我仍然会返回到attributedPlaceholder

iOS8 / 9 / Swift 2.0 – 工作示例

 func colorPlaceholderText(){ var multipleAttributes = [String : NSObject]() multipleAttributes[NSForegroundColorAttributeName] = UIColor.appColorCYAN() //OK - comment in if you want background color //multipleAttributes[NSBackgroundColorAttributeName] = UIColor.yellowColor() //OK - Adds underline //multipleAttributes[NSUnderlineStyleAttributeName] = NSUnderlineStyle.StyleDouble.rawValue let titleString = "Search port/country/vessel..." let titleAttributedString = NSAttributedString(string: titleString, attributes: multipleAttributes) self.textFieldAddSearch.attributedPlaceholder = titleAttributedString }