Swift change color of text using NSMutableAttributedStrings

r4id4 picture r4id4 · Sep 17, 2014 · Viewed 16.6k times · Source

I have a UITableView and i would like to display the text of each row using different colors within the same line.

I've tried this code, trying to translate from Obj-C but i cannot have it working

        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

The output of all this is enter image description here

where the number 34 correspond to object.valueForKey("example1")!.description, so the problem is that the number is not red, and the second part (object.valueForKey("example2")!.description) is replaced by {.

If I leave this piece of code regarding NSAttributedString the row text is displayed correctly.

Answer

Casey Fleser picture Casey Fleser · Sep 17, 2014

I think the problem might lie in assigning to cell.textLabel?.text instead of cell.textLabel?.attributedText. Perhaps something like this:

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

Wasn't sure if you wanted the second part of the string to be red or another color so I made it black.