2013-02-22 39 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