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
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.
Swift 4.2and Swift 5colorise parts of the string. A very easy way to use NSMutableAttributedString while extending the String. This also can be used to colourize more than one word in the whole string.
For formatting a part of a string, you need an attributed string which specifies parts of the string formatted in different ways. In this lesson we’ll learn how to work in attributed strings in Swift.
Let’s look at the setup for each. In Xcode use the Command-Shift-N keyboard shortcut to open a new project Swift3AttributedString. Use an iOS Application of a Single View Template. Go to the ViewController.Swift file, and clean out the ViewController class to look like this:
Color up text in textview within a specific range 1 Swift Text Attributes Color 118 Making text bold using attributed string in swift 21 bold part of string in UITextView swift
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With