Skip to content

Instantly share code, notes, and snippets.

@priore
Last active May 5, 2018 06:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save priore/4950044e6c944a20575207c054dec95f to your computer and use it in GitHub Desktop.
Save priore/4950044e6c944a20575207c054dec95f to your computer and use it in GitHub Desktop.
HTML string to NSAttributedString
// Swift 4
extension String {
func toAttributedString(color: UIColor?, font: UIFont?) -> NSAttributedString {
do {
var string = self
if color != nil, font != nil {
string = """
<style>
body {
color:\(color!.hex);
font-size:\(font!.pointSize)px;
font-family:'\(font!.fontName)';
}
</style>\(self)
"""
}
guard let data = string.data(using: .utf8) else {
return NSAttributedString(string: self)
}
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue]
let attrString = try NSMutableAttributedString(data: data, options: options, documentAttributes: nil)
return attrString
} catch {
print("error:", error)
return NSAttributedString(string: self)
}
}
}
@evermeer
Copy link

evermeer commented May 5, 2018

You don't have to go to HTML first to set a font on an attributed string. You can just use something like:

func toAttributedString(color: UIColor?, font: UIFont?) -> NSAttributedString {
   var attributedText = NSMutableAttributedString(string: self)
   attributedText.addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: attributedText.length))
   attributedText.addAttribute(NSAttributedStringKey.foregroundColor.rawValue, value: color, range: NSRange(location: 0, length: attributedText.length))
   return attributedText
}

For an easy to use attributed text helper see:
https://github.com/evermeer/AttributedTextView

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment