UILabel Text with Multiple Font Colors

前端 未结 8 612
一向
一向 2020-12-19 18:48

Is there a way to have the textColor property of a UILabel be two different UIColors? Basically I\'m trying to make the first characte

相关标签:
8条回答
  • 2020-12-19 19:18

    not currently possible, usually you would use an NSAttributedString, but to use this on iOS you would need to roll your own label. you may be able to work round this using a UIWebView, but I don't like to do that, it seems heavy handed.

    0 讨论(0)
  • 2020-12-19 19:24

    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;
    
    0 讨论(0)
  • 2020-12-19 19:25

    No, that's not possible - you need to draw on your own or compose using several labels.

    If you can accept 3.2 compatibility, you might have a look at NSAttributedString.

    0 讨论(0)
  • 2020-12-19 19:26

    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.)

    0 讨论(0)
  • 2020-12-19 19:30

    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;
    
    0 讨论(0)
  • 2020-12-19 19:39

    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:

    0 讨论(0)
提交回复
热议问题