0

I have a label with the string shown below. I would like secondVariable to be a different color. I think I understand how to change the color. My problem is getting the range of secondVariable.

let str = "\(firstVariable) some random text \(secondVariable)"

let secondVariableRange = str.range(???) 
let secondVariableNSRange = NSRange(secondVariableRange, in: str)

let attributedString = NSMutableAttributedString.init(string: 
    "\(firstVariable) some random text \(secondVariable)")

attributedString.addAttribute(.foregroundColor, value: UIColor.white, 
    range: NSRange(secondVariableNSRange, in: attributedString)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
squarehippo10
  • 1,855
  • 1
  • 15
  • 45

1 Answers1

0

There's a simpler approach than dealing with ranges. Build up your attributed string in pieces.

let attributedString = NSMutableAttributedString(string: 
"\(firstVariable) some random text ")
let attrs: [NSAttributedStringKey : Any] = [ .foregroundColor: UIColor.white ]
let secondString = NSAttributedString(string: "\(secondVariable)", attributes: attrs)
attributedString.append(secondString)

But if you really want to get the range, use:

let secondVariableRange = (str as NSString).range(of: "\(secondVariable)")
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I really thought that was going to be a little more complicated. It took me a second to figure out that I also needed to use myLabel.attributedText = ... instead of just myLabel.text = ... Thanks! – squarehippo10 May 24 '18 at 23:05