UILabel Text with Multiple Font Colors

2020-02-12 20:15发布

Is there a way to have the textColor property of a UILabel be two different UIColors? Basically I'm trying to make the first character in the UILabel text property to be greenColor and the rest be blackColor. I would like to avoid using two different UILabels because I may want to change the position in the text of the green character.

8条回答
等我变得足够好
2楼-- · 2020-02-12 20:46

Another alternative way is to create multiple labels with difference color and layout them next to each other. Try to make the label's background color transparent. It may be tedious but should work.

查看更多
狗以群分
3楼-- · 2020-02-12 20:47

UILabel doesnot supprt this property...

Use should use NSAttributedString... and use controllers for drawing NSAttributesString...

Controller for NSAttributedString

UPDATE:

From iOS 6 you can do the following :

label.attributedText = attributedString;
查看更多
成全新的幸福
4楼-- · 2020-02-12 20:50

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
    }

Result:

enter image description here

查看更多
成全新的幸福
5楼-- · 2020-02-12 20:52

Starting from ios 6 you can do the following :

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;
查看更多
淡お忘
6楼-- · 2020-02-12 20:53

NSAttributedStrings support mixed fonts, styles, and colors in the same string, but aren't currently supported by any standard UIKit controls. That said, you should check out TTTAttributedLabel. It's a simple, performant replacement for UILabel that will allow you to display rich text really easily.

查看更多
疯言疯语
7楼-- · 2020-02-12 20:54

No - Apple say you should use HTML in a UIWebView if you need formatted text. (See the note in the overview section of the UITextView API docs.)

查看更多
登录 后发表回答