简体   繁体   中英

Change font size of NSAttributedString

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM