Reputation: 1634
My app get some HTML formatted text from a website and I would like to change the font size of the NSAttributedString
and display it in a textview
var htmlString : String //the html formatted text
textView.attributedText = handleHtml(htmlString) // this is how I call the function, but the font size didn't change
func handleHtml(string : String) -> NSAttributedString{
let attrs = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSFontAttributeName: UIFont.systemFontOfSize(20.0)]
var returnStr = NSAttributedString()
do {
returnStr = try NSAttributedString(data: string.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: attrs, documentAttributes: nil)
} catch {
print(error)
}
return returnStr
}
I tried [NSFontAttributeName: UIFont.systemFontOfSize(20.0)]
as shown in the above code but the font size didn't changed.
Upvotes: 0
Views: 2104
Reputation: 1634
I just figured it out. I should use NSMutableAttributedString
instead of NSAttributedString
func handleHtml(string : String) -> NSAttributedString{
var returnStr = NSMutableAttributedString()
do {
returnStr = try NSMutableAttributedString(data: string.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
let fullRange : NSRange = NSMakeRange(0, returnStr.length)
returnStr.addAttributes([NSFontAttributeName : yourFont], range: fullRange)
} catch {
print(error)
}
return returnStr
}
Upvotes: 1