I'm trying to convert a HTML-String coming from my backend into a NSAttributedString
for my textView
, but I want to set the font myself.
Here is an example of a HTML-String coming from my server:
<p><strong>Title</strong></p> <p><strong>Extra info ..</strong></p><p>- Some more info</p> <p>- Contact</p>
Some stackoverflow topics suggest setting the font in the server-backend, however this isn't possible in my situation.
I searched online on how to create the NSAtrributedString
: use a WebView
or a NSAttributedString
, I went with the second for certain reasons. I use the following method to convert my HTML-String into a NSAttributedString:
func setHTMLFromString() -> NSAttributedString{
let attrStr = try! NSMutableAttributedString(
data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return attrStr
}
This method works, however it overrides the default System font I have set for my textView. So I tried adding the font as an attribute:
func setHTMLFromString() -> NSAttributedString{
let attrStr = try! NSMutableAttributedString(
data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
if #available(iOS 8.2, *) {
attrStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(16.0, weight: UIFontWeightThin),
NSForegroundColorAttributeName: UIColor(rgb: 0x555555)], range: NSMakeRange(0, attrStr.length))
} else {
attrStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(16.0),
NSForegroundColorAttributeName: UIColor(rgb: 0x555555)], range: NSMakeRange(0, attrStr.length))
}
return attrStr
}
Now the font I want to display does show correctly, however all the HTML tags stopped working. Anyone have a solution on how to set the font and keep the HTML tags working?