0

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.

Larme
  • 24,190
  • 6
  • 51
  • 81
hklel
  • 1,624
  • 23
  • 45
  • 3
    You can either change the font but adding some `NSString` (as HTML) set, or iterate through the final `NSAttributedString` to add your font (see there: http://stackoverflow.com/questions/19921972/parsing-html-into-nsattributedtext-how-to-set-font) The doc of `initWithData:options:documentAttributes:error:` says it clearly for `options` parameter that you can't set it there. – Larme Sep 16 '15 at 12:08

1 Answers1

1

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
}
hklel
  • 1,624
  • 23
  • 45