0

I'm trying to change the second half of some text to a different color using range.

        let stringToColor = NSLocalizedString("Plan", comment: "")
        let mainString = title + ": "  + stringToColor
        let range = (mainString as NSString).range(of: stringToColor)
        let attrString = NSMutableAttributedString(string: mainString)
        attrString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.orange, range: range)

The text gets outputted but all one color, not the one set using foregroundColor key. Just can't see what the issue is.

ty

user7684436
  • 697
  • 14
  • 39
  • Your code works for me. Run your code through the debugger. Look at each value and see where it goes wrong. – rmaddy May 27 '18 at 18:18
  • Your code doesn't seem to have an issue (Well I'd do it other way because `range(of:)` could cause issues). Question, on a `UILabel` or `UITextView`, do you correctly do `myLabel.attributedText = attrString` and not `myLabel.text = attrString.string`? Do you override `myLabel` properties at some point? – Larme May 27 '18 at 18:20
  • Q1: The first approach. Q2: Tried both approaches – user7684436 May 27 '18 at 18:24
  • Correctly setting `.attributedText` fixed the issue. Thanks! – user7684436 May 27 '18 at 18:28

0 Answers0