html - 如何在 iOS 中使用 NSAttributedString 为 HTML 链接着色

标签 html ios uitextview nsattributedstring

我使用 UITextView 来显示 HTML 内容,除了链接外,它工作正常。我可以像这样为普通文本设置字体和颜色:

let str = "<font size='4' style='color:red'>text is red</font>"

效果很好。但是当尝试像这样给链接上色时什么也没有发生。

let str = "some text <a href='http://stackoverflow.com' style='color:red'> 
              link is not red!?</a> some text <a href='http://google.com' 
              style='color:green'> link is not green!?</a>"

这就是我将字符串设置到 UITextView 的方式。

var attrStr = NSAttributedString(
        data: str.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil,
        error: nil)
myTextView.attributedText = attrStr

编辑:

可以使用此代码编辑所有链接颜色。不可能根据链接使用不同的颜色,这正是我想要的。

myTextView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.greenColor()]

最佳答案

在 iOS 7 上,您可以设置 UITextView 的 tintColor。它会影响链接颜色以及光标线和所选文本颜色。

iOS 7 还向 UITextView 添加了一个名为 linkTextAttributes 的新属性,它似乎可以让您完全控制链接样式。

引用链接:Can I change the color of auto detected links on UITextView?

iOS 开发者库链接:iOS Developer UITextView Class

引用上面的链接,希望对你有帮助。

关于html - 如何在 iOS 中使用 NSAttributedString 为 HTML 链接着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895404/

相关文章:

html - NavBar h1 元素卡在顶部

html - node.js express 使用样式表/脚本

cocoa-touch - UINavigationBar 右键不显示

ios - 自适应 uitextview 直到特定高度

ios - 在 UITableViewCell 中的 UITextView 中设置多个链接

ios - 在 UITextView 中格式化文本

javascript - 如何在html中自定义柱形图

html - 如何设置带边框的 100% 高度的 Div?

ios - 如何在 Swift3.0 中居中对齐 UICollectionView 的单元格?

ios - 在 iOS 中使用循环动画​​背景