2013-02-22 113 views
13

我试图在我的文本框的占位符斜体,由于我的应用程序的目标是iOS 6.0或以上更新,决定用attributedPlaceholder属性,而不是滚动的东西更多的自定义的。代码如下:的UITextField 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工作?

+1

我可以重现你的问题,我想这是iOS中的一个错误。 – Florian 2013-02-22 19:50:45

回答

16

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

您可以通过创建文本字段的委托和利用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; 
} 
10

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

作为一种解决办法,我建议压倒一切drawPlaceholderInRect:和图纸自己的占位符。另外,你应该在这个文件上写一个雷达,并且包含一个演示该bug的最小示例项目。

+0

看来,drawPlaceholderInRect:不会在UITextField中调用。见http://stackoverflow.com/questions/1920783/drawtextinrect-on-uitextfield-not-called – 2013-02-24 15:38:16

+0

请忽略我的意见,说了这么问题是旧的,现在看来工作。 – 2013-02-24 15:58:55

8

我只是在这个问题上绊倒自己。显然,占位符将采用任何字体的文本字段分配。只需设置文本字段的字体,你就很好。

对于一切,像占位符的颜色,我还是回去attributedPlaceholder

+0

真棒回答。为我工作! – nimeshdesai 2013-06-21 22:42:25

-1

iOS8上/ 9 /雨燕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 
} 
+0

这适用于颜色。但不是字体本身 – dmclean 2016-07-08 18:12:31