priore

HTML string to NSAttributedString

May 4th, 2018
154
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×