我不敢相信我在问这个问题,但是(一直在找一个半小时而没有运气的答案)...如何将NSAttributedText附加到UITextView? (在Swift 2.0+中)
我正在构建一个从服务器上下载项目的工具,当它们进来时,我想添加AttributedText并添加绿色(表示成功)或添加红色(表示失败)。
为此,我相信我需要NSMutableAttributedString,但是UITextView仅具有NSattributedString,该NSattributedString无法访问appendAttributedString(attrString: NSAttributedString NSAttributedString)
因此,如果我有一个带有NSAttributedString的UITextView,上面写着红色的“正在加载”,我该如何在文本“正在加载”之后添加绿色的“成功”文本。
例如这样:
<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
}
}
最佳答案
您可以使用NSAttributedString
将NSMutableAttributedString
转换为mutableCopy()
,而copy()
会为您做相反的事情,如下所示:
let string1 = NSAttributedString(string: "loading", attributes: [NSForegroundColorAttributeName: UIColor.redColor()])
let string2 = NSAttributedString(string: "success", attributes: [NSForegroundColorAttributeName: UIColor.greenColor()])
let newMutableString = string1.mutableCopy() as! NSMutableAttributedString
newMutableString.appendAttributedString(string2)
textView.attributedText = newMutableString.copy() as! NSAttributedString
由于
mutableCopy()
和copy()
都返回AnyObject
,这有点尴尬,因此您需要始终使用as!
将它们转换为正确的类型。