将NSAttributed文本附加到UITextview



我不敢相信我会问这个问题,但(已经找了一个半小时的答案,但没有运气)如何将NSAttributedText附加到UITextView(Swift 2.0+)

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

要做到这一点,我相信我需要NSMutableAttributedString,但UITextView只有NSattributedString,它不能访问appendAttributedString(attrString: NSAttributedString NSAttributedString)

因此,如果我有一个UITextView,上面有一个NSAttributedString,上面用红色写着"loading",我如何用绿色的"success"来附加文本"loading"。

例如:

<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
    }
}

您可以使用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()都返回AnyObject,所以您需要始终使用as!将它们转换为正确的类型。

    let loadingMessage = NSMutableAttributedString(string: "loading...")
    loadingMessage.addAttribute(NSStrokeColorAttributeName, value: UIColor.redColor(), range: NSRange(location: 0, length: 10))
    let textView = UITextView()
    textView.attributedText = loadingMessage

最新更新