Search code examples
iosswiftxcodeswift2uilabel

Is it possible to set a different colour for one character in a UILabel?


I've been working on a small project using Xcode. It uses a lot of labels, textfields, etc. I've finished with most of the layout, the constrains, and the forms, titles, etc. After which, the client announces that for all required fields, there should be a red asterisk next to the label.

Call me lazy, but I'd rather not go back to all of my forms, add in a lot of labels with asterisks on them, and re-do my auto-layout to accommodate the new labels.

So, is there a way to change the colour of a specific character (in this case, the asterisk) in a UILabel, while the rest of the text stays black?


Solution

  • You can use NSMutableAttributedString. You can set specific range of your string with different color, font, size, ...

    E.g:

     var range = NSRange(location:2,length:1) // specific location. This means "range" handle 1 character at location 2
    
     attributedString = NSMutableAttributedString(string: originalString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
     // here you change the character to red color
     attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
     label.attributedText = attributedString
    

    Ref: Use multiple font colors in a single label - Swift

    You can change a lot of attribute of String. Ref from apple: https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html