UILabel text with multiple font colors

Is there a way to have a property textColorfor UILabeltwo different UIColors? Basically I try to make the first character UILabel text propertyequal greenColor, and the rest - blackColor. I would like to avoid using two different ones UILabels, because I can change the position in the text of the green symbol.

+3
source share
8 answers

UILabel does not support this property ...

Usage should use NSAttributedString ... and use controllers to draw NSAttributesString ...

Controller for NSAttributedString

UPDATE:

From iOS 6, you can do the following:

label.attributedText = attributedString;
+4

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;
+7

NSAttributedStrings , , UIKit. , TTTAttributedLabel. , UILabel, .

+2

. Apple , HTML UIWebView, . (. API UITextView.)

+1

- . . , .

+1

Swift 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

+1

, - .

3.2, NSAttributedString.

0

, NSAttributedString, iOS . UIWebView, , , .

0

Source: https://habr.com/ru/post/1777495/


All Articles