简体   繁体   English

更改NSAttributedString的字体大小

[英]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 我的应用程序从网站上获取了一些HTML格式的文本,我想更改NSAttributedString的字体大小并将其显示在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. 如上面的代码所示,我尝试了[NSFontAttributeName: UIFont.systemFontOfSize(20.0)] ,但是字体大小没有变化。

I just figured it out. 我只是想通了。 I should use NSMutableAttributedString instead of NSAttributedString 我应该使用NSMutableAttributedString而不是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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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