【发布时间】:2016-04-18 22:34:36
【问题描述】:
我不敢相信我在问这个问题,但是(一直在寻找答案一个半小时没有运气)...如何将 NSAttributedText 附加到 UITextView?(在 Swift 2.0+ 中)
我正在构建一个从我的服务器下载项目的工具,当它们进入时,我想添加绿色表示成功或红色表示失败的 AttributedText。
为此,我认为我需要 NSMutableAttributedString,但 UITextView 只有 NSattributedString,它无法访问 appendAttributedString(attrString: NSAttributedString NSAttributedString)
所以,如果我有一个 UITextView,上面有一个 NSAttributedString,上面写着红色的“正在加载”,我如何追加文本“正在加载”以及绿色的“成功”文本。
例如这样:
<font color="red">loading</font><font color="green">success</font>
更新
我找到了我的问题的答案,但我觉得不是最佳答案。
let loadingMessage = NSMutableAttributedString(string: "loading...\n")
loadingMessage.addAttribute(NSStrokeColorAttributeName, value: UIColor.redColor(), range: NSRange(location: 0, length: 10))
progressWindowViewController.theTextView.attributedText = loadingMessage
loadingMessage.appendAttributedString("<font color=\"#008800\">Successfully Synced Stores...</font>\n".attributedStringFromHtml!)
progressWindowViewController.theTextView.attributedText = loadingMessage
我上面的答案有效,但通过覆盖整个文本来实现(并且每次绘制时都会继续这样做)。我想知道是否有一种真正的方法将字符串附加到末尾以获得最佳性能?
我用于 HTML 的扩展名
extension String {
var attributedStringFromHtml: NSAttributedString? {
do {
return try NSAttributedString(data: self.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch _ {
print("Cannot create attributed String")
}
return nil
}
}
【问题讨论】:
标签: ios swift2 uitextview nsattributedstring nsmutableattributedstring