Skip to content

Instantly share code, notes, and snippets.

@iamjason
Last active March 9, 2017 21:10
Show Gist options
  • Save iamjason/504b79fd9a6efdc7a23e75e494738d67 to your computer and use it in GitHub Desktop.
Save iamjason/504b79fd9a6efdc7a23e75e494738d67 to your computer and use it in GitHub Desktop.
HTML to NSAttributedString
import UIKit
public extension String {
static let htmlBase = "<html><head><style type='text/css'> body { color: %COLOR%; } %STYLE% </style></head><body>%BODY%</body></html>"
static let cssBase = " h1 { font-family: 'GTWalsheimLight'; font-size: 34px; } h2 { font-family: 'GTWalsheimBold'; font-size: 24px; } h3 { font-family:'GTWalsheimLight'; font-size: 18px; } h4 { font-family:'GTWalsheimBold'; font-size: 14px; } h5 { font-family:'GTWalsheimBold'; font-size: 12px; } p { font-family: 'SourceSansPro-Regular'; font-size: 16px; } p.strong { font-family: 'SourceSansPro-Semibold'; font-size: 16px; }"
public func HTMLtoAttributedText(_ color:UIColor = UIColor.black, css:String = String.cssBase) -> NSAttributedString? {
// maybe break this out into a string extension, but
// for now... lets just leave it here
func hexString(_ c:UIColor) -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
c.getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
let combined = (String.htmlBase as NSString)
.replacingOccurrences(of: "%BODY%", with: self)
.replacingOccurrences(of: "%COLOR%", with: hexString(color) )
.replacingOccurrences(of: "%STYLE%", with: css)
if let data = combined.data(using: .utf8) {
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
}
catch {
print("error creating attributed string")
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment