Advertisement
priore

HTML string to NSAttributedString

May 4th, 2018
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.20 KB | None | 0 0
  1. // Swift 4
  2. extension String {
  3.  
  4.     func toAttributedString(color: UIColor?, font: UIFont?) -> NSAttributedString {
  5.        
  6.         do {
  7.            
  8.             var string = self
  9.             if color != nil, font != nil {
  10.                 string = """
  11.                    <style>
  12.                        body {
  13.                            color:\(color!.hex);
  14.                            font-size:\(font!.pointSize)px;
  15.                            font-family:'\(font!.fontName)';
  16.                        }
  17.                    </style>\(self)
  18.                """
  19.             }
  20.            
  21.             guard let data = string.data(using: .utf8) else {
  22.                 return NSAttributedString(string: self)
  23.             }
  24.            
  25.             let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue]
  26.            
  27.             let attrString = try NSMutableAttributedString(data: data, options: options, documentAttributes: nil)
  28.  
  29.             return attrString
  30.         } catch {
  31.             print("error:", error)
  32.             return  NSAttributedString(string: self)
  33.         }
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement