Skip to content

Instantly share code, notes, and snippets.

@Tulakshana
Last active October 17, 2017 13:09
Show Gist options
  • Save Tulakshana/8ac711e022bb75c14b4fde52a91d3c7d to your computer and use it in GitHub Desktop.
Save Tulakshana/8ac711e022bb75c14b4fde52a91d3c7d to your computer and use it in GitHub Desktop.
A convenience method create an attributed string from a plain html string and apply a font of your choice. The method could be modified to support any fonts and styles.
enum FontName: String {
case timesNewRoman = "TimesNewRomanPSMT"
case timesNewRomanItalic = "TimesNewRomanPS-ItalicMT"
case timesNewRomanBold = "TimesNewRomanPS-BoldMT"
}
extension UIFont {
class var sanFranciscoRegular: UIFont {
if let font = UIFont.init(name: "SFUIText-Regular", size: 15) {
return font
}
return UIFont.systemFont(ofSize: 15)
}
class var sanFranciscoItalic: UIFont {
if let font = UIFont.init(name: "SFUIText-Italic", size: 15) {
return font
}
return UIFont.italicSystemFont(ofSize: 15)
}
class var sanFranciscoBold: UIFont {
if let font = UIFont.init(name: "SFUIText-Bold", size: 15) {
return font
}
return UIFont.boldSystemFont(ofSize: 15)
}
}
class AttribManipulator {
static func attributedStringFromHTML(html: String) -> NSAttributedString {
guard let data = html.data(using: .utf8) else { return NSAttributedString() }
do {
let att = try NSAttributedString(data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
documentAttributes: nil)
let matt = NSMutableAttributedString.init(attributedString: att)
att.enumerateAttributes(in: NSRange.init(location: 0, length: att.length),
options: .longestEffectiveRangeNotRequired,
using: { (list: [String : Any], range: NSRange, _) in
if let font: UIFont = list[NSFontAttributeName] as? UIFont {
switch font.fontName {
case FontName.timesNewRoman.rawValue:
matt.addAttribute(NSFontAttributeName, value: UIFont.sanFranciscoRegular, range: range)
case FontName.timesNewRomanItalic.rawValue:
matt.addAttribute(NSFontAttributeName, value: UIFont.sanFranciscoItalic, range: range)
case FontName.timesNewRomanBold.rawValue:
matt.addAttribute(NSFontAttributeName, value: UIFont.sanFranciscoBold, range: range)
default:
matt.addAttribute(NSFontAttributeName,
value: UIFont.init(name: font.fontName, size: 15.0)!,
range: range)
}
}
})
return matt
} catch {
return NSAttributedString()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment