UITextField的attributesPlaceholder无效

时间:2013-02-22 19:20:06

标签: ios uitextfield nsattributedstring

我正在尝试将文本字段中的占位符设置为斜体,并且由于我的应用程序针对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工作的是什么?

4 个答案:

答案 0 :(得分:17)

正如沃伦所指出的那样,造型目前无法像你尝试的那样完成。一个好的解决方法是按照您希望占位符查看的方式设置文本字段的字体属性,然后在用户开始键入时更改文本字段的字体。看起来像占位符和文本是不同的字体。

您可以通过创建textfield的委托并使用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;
}

答案 1 :(得分:10)

这几乎肯定是一个错误。 documentation for the attributedPlaceholder property声称无论前景颜色属性如何,都将使用灰色绘制字符串,但情况并非如此:您可以同时设置前景色和背景色。不幸的是,font属性似乎被剥离并恢复为系统字体。

作为一种解决方法,我建议覆盖drawPlaceholderInRect:并自行绘制占位符。此外,您应该在此处提交一个Radar,并包含一个演示该错误的最小示例项目。

答案 2 :(得分:8)

我自己偶然发现了这个问题。显然,占位符将采用文本字段分配的任何字体。只需设置textfield的字体就可以了。

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

答案 3 :(得分:-1)

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
}