将 NSAttributed 文本附加到 UITextview

Append NSAttributed text to UITextview

我不敢相信我会问这个问题,但是(一直在寻找一个半小时的答案,但没有成功)...如何将 NSAttributedText 附加到 UITextView?(在 Swift 2.0+ 中)

我正在构建一个从我的服务器下载项目的工具,当它们进入时,我想添加带有绿色表示成功或红色表示失败的 AttributedText。

为此,我相信我需要 NSMutableAttributedString,但 UITextView 只有 NSattributedString,它无法访问 appendAttributedString(attrString: NSAttributedString NSAttributedString)

因此,如果我有一个带有 NSAttributedString 的 UITextView,它上面写着 "loading" 红色,我如何 append 文本 "loading" 与文本绿色 "success".

例如像这样:

<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
    }
}
    let loadingMessage = NSMutableAttributedString(string: "loading...")
    loadingMessage.addAttribute(NSStrokeColorAttributeName, value: UIColor.redColor(), range: NSRange(location: 0, length: 10))

    let textView = UITextView()
    textView.attributedText = loadingMessage

您可以使用 mutableCopy()NSAttributedString 转换为 NSMutableAttributedString,而 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() return AnyObject,所以您需要使用 as! 将它们转换为始终正确输入。