2010-11-29 90 views
3

有沒有辦法讓UILabeltextColor屬性成爲兩個不同的UIColors?基本上我試圖使UILabeltext property中的第一個字符爲greenColor,其餘的爲blackColor。我想避免使用兩種不同的UILabels,因爲我可能想要改變綠色字符文本中的位置。具有多種字體顏色的UILabel文本

回答

4

的UILabel亙古不變的supprt此屬性...

使用時應使用NSAttributedString ...並使用控制器繪製NSAttributesString ...

Controller for NSAttributedString

UPDATE:

從iOS 6您可以執行以下操作:

label.attributedText = attributedString; 
+1

請參閱本疑問句我已經acieved你想要什麼http://stackoverflow.com/questions/4208282/advance-search-implementation-in-iphone/4208329#4208329 – KingofBliss 2010-11-29 17:27:08

+1

Downvoted指向我們的代碼,而不是直接回答大的存儲庫。 – 2011-04-04 17:59:29

0

不,這是不可能的 - 你需要自己繪畫或使用幾個標籤來撰寫。

如果您可以接受3.2兼容性,則可以查看NSAttributedString

0

目前不可能,通常您會使用NSAttributedString,但要在iOS上使用此功能,您需要滾動自己的標籤。你可以用UIWebView來解決這個問題,但我不喜歡這樣做,這看起來很重要。

1

否 - 如果您需要格式化文本,Apple會說您應該在UIWebView中使用HTML。 (請參閱UITextView API docs的概述部分中的註釋。)

1

另一種替代方法是創建具有不同顏色的多個標籤並將它們彼此相鄰排列。嘗試使標籤的背景顏色透明。這可能是乏味的,但應該工作。

2

NSAttributedStrings支持同一字符串中的混合字體,樣式和顏色,但目前不支持任何標準UIKit控件。也就是說,你應該檢查出TTTAttributedLabel。這是一個簡單的,高性能的UILabel替代品,可以讓你真正輕鬆地顯示豐富的文本。

7

從iOS 6中開始,你可以做到以下幾點:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string]; 
[attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,3)]; 
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(4,9)]; 
cell.label.attributedText = attributedString; 
1

斯威夫特3

extension NSMutableAttributedString { 
     func setColorForText(textToFind: String, withColor color: UIColor) { 
     let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive) 
      if range != nil { 
      self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) 
      } 
     } 

} 


func setColoredLabel() { 
     var string: NSMutableAttributedString = NSMutableAttributedString(string: "My label with red blue and green colored text") 
     string.setColorForText(textToFind: "red", withColor: UIColor.red) 
     string.setColorForText(textToFind: "blue", withColor: UIColor.blue) 
     string.setColorForText(textToFind: "green", withColor: UIColor.green) 
     mylabel.attributedText = string 
    } 

結果:

enter image description here