Last active
May 5, 2018 06:51
-
-
Save priore/4950044e6c944a20575207c054dec95f to your computer and use it in GitHub Desktop.
HTML string to NSAttributedString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't have to go to HTML first to set a font on an attributed string. You can just use something like:
For an easy to use attributed text helper see:
https://github.com/evermeer/AttributedTextView