更改NSAttributedString的字体大小

时间:2015-09-16 11:39:40

标签: ios swift nsattributedstring

我的应用从网站上获取一些HTML格式的文字,我想更改NSAttributedString的字体大小并在文本视图中显示

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
}

我尝试[NSFontAttributeName: UIFont.systemFontOfSize(20.0)],如上面的代码所示,但字体大小没有改变。

1 个答案:

答案 0 :(得分:1)

我只是想通了。我应该使用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
}