0

How do I change the text in my UITableView to two different colors?

    let highest = (history[indexPath.row].highest!)   //Red color
    let lowest = (history[indexPath.row].lowest!)     //Green color
    cell.detailTextLabel?.text = "$\(highest)/$\(lowest)"

    return cell

Thank you!

14079_Z
  • 401
  • 5
  • 20

3 Answers3

0

your output will look like that :

enter image description here

you can do it simply like that

    //your constants
    let highest = (history[indexPath.row].highest!)   //Red color
    let lowest = (history[indexPath.row].lowest!)     //Green color

    // a string combining them 
    let concatOfHighestLowest = "$\(highest)/$\(lowest)"

    //the attributed mutable string .
    let finalString = NSMutableAttributedString(string: concatOfHighestLowest)
     // 1 in NSRange Locations stands for the "$" symbol.
    finalString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:1,length:highest.count))
     // highest.count + 3 in NSRange stands for the "$ , /" symbols and after the highest value.
    finalString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.green, range: NSRange(location:highest.count + 3,length:lowest.count))




    cell.detailTextLabel?.attributedText = finalString

    return cell
MhmdRizk
  • 1,591
  • 2
  • 18
  • 34
0

Use NSMutableAttributedString

let myString = NSMutableAttributedString(string: "$\(highest)/$\(lowest)" )
let heighestRange = myString.mutableString.range(of: highest)
myString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: heighestRange)
let lowestRange = myString.mutableString.range(of: lowest)
myString.addAttribute(.foregroundColor, value: UIColor.green, range: lowestRange)
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
0
extension NSMutableAttributedString {

    func setColor(color: UIColor, forText stringValue: String) {
        let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

By using the above extension you can set text color for label like below

    let highest = "160"   //Red color
    let lowest = "80"     //Green color
    let stringValue = "$\(highest)/$\(lowest)"
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
    attributedString.setColor(color: UIColor.red, forText: highest)
    attributedString.setColor(color: UIColor.green, forText: lowest)
    self.testLabel.attributedText = attributedString

Output Will be like below

enter image description here

Vinodh
  • 5,262
  • 4
  • 38
  • 68