Use multiple font colors in a single label
IosSwiftUilabelNsattributedstringTextcolorIos Problem Overview
Is there a way to use two, or even three font colors in a single label in iOS?
If the text "hello, how are you" were used as an example, the "hello," would be blue, and the "how are you" would be green?
Is this possible, it seems easier than creating multiple labels?
Ios Solutions
Solution 1 - Ios
First of all initialize of you NSString and NSMutableAttributedString as below.
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
In ViewDidLoad
override func viewDidLoad() {
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
// set label Attribute
labName.attributedText = myMutableString
super.viewDidLoad()
}
OUTPUT
MULTIPLE COLOR
Add the line code below in your ViewDidLoad to get multiple colors in a string.
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))
Multiple color OUTPUT
Swift 4
var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))
Swift 5.0
var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))
Solution 2 - Ios
For @Hems Moradiya
let attrs1 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.greenColor()]
let attrs2 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.whiteColor()]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.appendAttributedString(attributedString2)
self.lblText.attributedText = attributedString1
Swift 4
let attrs1 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.green]
let attrs2 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.white]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1
Swift 5
let attrs1 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.green]
let attrs2 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.white]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1
Solution 3 - Ios
Swift 4
By using following extension function, you can directly set a color attribute to an attributed string and apply the same on your label.
extension NSMutableAttributedString {
func setColorForText(textForAttribute: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
// Swift 4.2 and above
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
// Swift 4.1 and below
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
Try above extension, using a label:
let label = UILabel()
label.frame = CGRect(x: 60, y: 100, width: 260, height: 50)
let stringValue = "stackoverflow"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textForAttribute: "stack", withColor: UIColor.black)
attributedString.setColorForText(textForAttribute: "over", withColor: UIColor.orange)
attributedString.setColorForText(textForAttribute: "flow", withColor: UIColor.red)
label.font = UIFont.boldSystemFont(ofSize: 40)
label.attributedText = attributedString
self.view.addSubview(label)
Result:
Solution 4 - Ios
Here a solution for Swift 5
let label = UILabel()
let text = NSMutableAttributedString()
text.append(NSAttributedString(string: "stack", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]));
text.append(NSAttributedString(string: "overflow", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray]))
label.attributedText = text
Solution 5 - Ios
Updated Answer for Swift 4
You can easily use html inside attributedText property of the UILabel to easily do various text formatting.
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Updated Answer for Swift 2
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Solution 6 - Ios
I liked it this way
let yourAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]
let yourOtherAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25)]
let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)
let combination = NSMutableAttributedString()
combination.append(partOne)
combination.append(partTwo)
Solution 7 - Ios
Used rakeshbs's answer to create an extension in Swift 2:
// StringExtension.swift
import UIKit
import Foundation
extension String {
var attributedStringFromHtml: NSAttributedString? {
do {
return try NSAttributedString(data: self.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch _ {
print("Cannot create attributed String")
}
return nil
}
}
Usage:
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
label.attributedText = htmlString.attributedStringFromHtml
Or even for one-liners
label.attributedText = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>".attributedStringFromHtml
The good thing about the extension is that you'll have .attributedStringFromHtml
attribute for all String
s throughout your whole application.
Solution 8 - Ios
UPDATE for SWIFT 5
func setDiffColor(color: UIColor, range: NSRange) {
let attText = NSMutableAttributedString(string: self.text!)
attText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
attributedText = attText
}
SWIFT 3
In my code , i create an extension
import UIKit
import Foundation
extension UILabel {
func setDifferentColor(string: String, location: Int, length: Int){
let attText = NSMutableAttributedString(string: string)
attText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueApp, range: NSRange(location:location,length:length))
attributedText = attText
}
}
and this for use
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.setDifferentColor(string: titleLabel.text!, location: 5, length: 4)
}
Solution 9 - Ios
Make use of NSMutableAttributedString
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
See more details here swift-using-attributed-strings
Solution 10 - Ios
Swift 3.0
let myMutableString = NSMutableAttributedString(
string: "your desired text",
attributes: [:])
myMutableString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.blue,
range: NSRange(
location:6,
length:7))
For more colors you can just keep adding attributes to the mutable string. More examples here.
Solution 11 - Ios
If you want to use this many times in your application you can just create the extension of the UILabel and it will make more simple:-
Swift 5
extension UILabel {
func setSpannedColor (fullText : String , changeText : String ) {
let strNumber: NSString = fullText as NSString
let range = (strNumber).range(of: changeText)
let attribute = NSMutableAttributedString.init(string: fullText)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
self.attributedText = attribute
}
}
Use your label:-
yourLabel = "Hello Test"
yourLabel.setSpannedColor(fullText: totalLabel.text!, changeText: "Test")
Solution 12 - Ios
Swift 4 UILabel Extension
In my case, I needed to be able to set different colors/fonts within labels frequently so I made a UILabel extension using Krunal's NSMutableAttributedString extension.
func highlightWords(phrases: [String], withColor: UIColor?, withFont: UIFont?) {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
for phrase in phrases {
if withColor != nil {
attributedString.setColorForText(textForAttribute: phrase, withColor: withColor!)
}
if withFont != nil {
attributedString.setFontForText(textForAttribute: phrase, withFont: withFont!)
}
}
self.attributedText = attributedString
}
It can be used like this:
yourLabel.highlightWords(phrases: ["hello"], withColor: UIColor.blue, withFont: nil)
yourLabel.highlightWords(phrases: ["how are you"], withColor: UIColor.green, withFont: nil)
Solution 13 - Ios
Use cocoapod Prestyler:
Prestyle.defineRule("*", Color.blue)
Prestyle.defineRule("_", Color.red)
label.attributedText = "*This text is blue*, _but this one is red_".prestyled()
Solution 14 - Ios
Swift 3 example using the HTML version.
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Solution 15 - Ios
Here is the code which supports Latest version of Swift as on Mar 2017.
Swift 3.0
Here I have created a Helper class and method for the
public class Helper {
static func GetAttributedText(inputText:String, location:Int,length:Int) -> NSMutableAttributedString {
let attributedText = NSMutableAttributedString(string: inputText, attributes: [NSFontAttributeName:UIFont(name: "Merriweather", size: 15.0)!])
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0) , range: NSRange(location:location,length:length))
return attributedText
}
}
In the Method Parameters, inputText:String - your Text to be displayed in label location:Int - where the style should be application, "0" as start of the string or some valid value as character position of the string length:Int - From the location until how many characters this style is applicable.
Consuming in other method:
self.dateLabel?.attributedText = Helper.GetAttributedText(inputText: "Date : " + (self.myModel?.eventDate)!, location:0, length: 6)
Output:
Note: The UI Color can be defined color as UIColor.red
or user defined colors as UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0)
Solution 16 - Ios
func MultiStringColor(first:String,second:String) -> NSAttributedString
{
let MyString1 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.PUREBLACK]
let MyString2 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.GREENCOLOR]
let attributedString1 = NSMutableAttributedString(string:first, attributes:MyString1)
let attributedString2 = NSMutableAttributedString(string:second, attributes:MyString2)
MyString1.append(MyString2)
return MyString1
}
Solution 17 - Ios
for using this NSForegroundColorAttributeName in swift lower version you can get unresolved identifier issues change the above to NSAttributedStringKey.foregroundColor.
swift lower version swift latest version
i.e., NSForegroundColorAttributeName == NSAttributedStringKey.foregroundColor
Solution 18 - Ios
Swift 4.2
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
var stringAlert = self.phoneNumber + "로\r로전송인증번호를입력해주세요"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringAlert, attributes: [NSAttributedString.Key.paragraphStyle:paragraphStyle, .font: UIFont(name: "NotoSansCJKkr-Regular", size: 14.0)])
attributedString.setColorForText(textForAttribute: self.phoneNumber, withColor: UIColor.init(red: 1.0/255.0, green: 205/255.0, blue: 166/255.0, alpha: 1) )
attributedString.setColorForText(textForAttribute: "로\r로전송인증번호를입력해주세요", withColor: UIColor.black)
self.txtLabelText.attributedText = attributedString