【问题标题】:Swift - HTML stylised NSAttributedString with linksSwift - 带有链接的 HTML 风格化 NSAttributedString
【发布时间】:2017-01-19 20:02:15
【问题描述】:

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

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

【问题讨论】:

  • 使用addAttributes() 代替setAttributes()?
  • 做到了!多么愚蠢的错误......谢谢

标签: swift uitextview nsattributedstring


【解决方案1】:

对于任何来访的人来说,@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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    相关资源
    最近更新 更多