使用NSMutableAttributedStrings快速更改文本颜色

r4i*_*id4 6 textcolor uitableview nsattributedstring ios swift

我有一个UITableView,我想在同一行中使用不同的颜色显示每一行的文本.

我试过这个代码,尝试从Obj-C翻译,但我不能让它工作

        let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject

        var attrString: NSMutableAttributedString = NSMutableAttributedString(string: object.valueForKey("example1")!.description)
        attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, attrString.length))

        var stringToCell:String = String(format: "%@    %@", attrString, object.valueForKey("example2")!.description)
        cell.textLabel?.text = stringToCell
Run Code Online (Sandbox Code Playgroud)

这一切的输出是 在此输入图像描述

数字34对应的地方object.valueForKey("example1")!.description,问题是数字不是红色,第二部分(object.valueForKey("example2")!.description)替换为{.

如果我留下关于NSAttributedString行文本的这段代码正确显示.

Cas*_*ser 11

我认为问题可能在于分配cell.textLabel?.text而不是cell.textLabel?.attributedText.也许是这样的:

let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject

var attrString: NSMutableAttributedString = NSMutableAttributedString(string: object.valueForKey("example1")!.description)
attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, attrString.length))

var descString: NSMutableAttributedString = NSMutableAttributedString(string:  String(format: "    %@", object.valueForKey("example2")!.description))
descString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(0, descString.length))

attrString.appendAttributedString(descString);
cell.textLabel?.attributedText = attrString
Run Code Online (Sandbox Code Playgroud)

不确定你是否希望字符串的第二部分是红色或其他颜色,所以我把它变黑了.