Swift - HTML 带有链接的程式化 NSAttributedString

Swift - HTML stylised NSAttributedString with links

我有一个 UITextView,我有一个 HTML 的字符串,我这样给它...

func applyHTML() {

    textView.attributedText = htmlString()
    textView.linkTextAttributes = [NSForegroundColorAttributeName: .blue,
                               NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
                               NSFontAttributeName:font]

}

func htmlString() -> NSAttributedString? {

    if let htmlData = text.dataUsingEncoding(NSUnicodeStringEncoding) {

        do {

            let attributedString = try NSMutableAttributedString(data: htmlData,
                                                                 options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                                                 documentAttributes: nil)


            return attributedString


        } 
        catch { return nil }
    }

    return nil
}

这很好用,我得到了带有黑色文本的蓝色超链接...我现在想做的是为所有非超链接文本设置字体样式和颜色...问题是当我这样做时,通过添加这个....

let length = attributedString.length
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center

attributedString.setAttributes([NSForegroundColorAttributeName:.white,NSFontAttributeName: myFont,NSParagraphStyleAttributeName: paragraphStyle], range: NSRange(location: 0, length: length))

它删除了超链接...我希望它们协同工作。我做错了什么?

对于任何访问过的人来说,@Larme 是对的

attributedString.setAttributes([NSForegroundColorAttributeName:.white,NSFontAttributeName: myFont,NSParagraphStyleAttributeName: paragraphStyle], range: NSRange(location: 0, length: length))

应该是

attributedString.addAttributes([NSForegroundColorAttributeName:.white,NSFontAttributeName: myFont,NSParagraphStyleAttributeName: paragraphStyle], range: NSRange(location: 0, length: length))