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 Strings throughout your whole application.
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)
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.
for using this NSForegroundColorAttributeName in swift lower version you can get unresolved identifier issues change the above to NSAttributedStringKey.foregroundColor.
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
}
Prestyle.defineRule("*", Color.blue)
Prestyle.defineRule("_", Color.red)
label.attributedText = "*This text is blue*, _but this one is red_".prestyled()