Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement