Swift - 带链接的 HTML 风格化 NSAttributedString

标签 swift uitextview nsattributedstring

我有一个 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))

关于Swift - 带链接的 HTML 风格化 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41750668/

相关文章:

ios - 计算适合固定矩形 TextView 的字符

objective-c - UILables、文本流和布局

iphone - iOS 7 上的 UITextView contentOffset

ios - paragraphSpacing 不是在段落之后设置空格,而是在\n之后设置空格

ios - Swift 中的 parser.parse() 导致 EXC_BAD_ACCESS

ios - swift : How to get the string before a certain character?

ios - Firebase 动态链接无效并被阻止

ios - 执行简单的 POST 请求 Swift

ios - 当文本有多行时,在UILabel中查找属性文本的宽度

ios - NSAttributedString 如何使用 NSParagraphStyle 设置文本行居中对齐