-1

I have a label in a custom cell which displays some info. The info will different in every cell and I would like to change the colour of a few 'keywords' inside the label so that they stand out.

I've tried the approach of converting the text to a NSMutableAttributedString and changing the colour of the text at a certain index. However, the location of the keyword in the text is different in every sentence. Is there any way to add something around the keywords so that they can be identified easily?

Edit: This answered my question:

Changing specific text's color using NSMutableAttributedString in Swift

TOPCOD3R
  • 226
  • 1
  • 3
  • 11
  • You can with `NS(Mutable)AttributedString` and that's out you need to do it. Your issue is not about UILabel, is how to find the range of your keyword. So: how to find a substring inside a string. Plenty of question already about that. What have you tried? – Larme Jul 08 '19 at 10:14

1 Answers1

1

You can do with attirbutedSring. Do not forget change font.

 let string1 = "Your string";
 let string2 = "your string 2";
 let attributedString = NSMutableAttributedString(string: "“\(string1)” \(string2)", attributes: [
            .font: UIFont(name: "IBMPlexSans", size: 15.0)!,
            .foregroundColor: UIColor(red: 128.0 / 255.0, green: 130.0 / 255.0, blue: 135.0 / 255.0, alpha: 1.0),
            .kern: 0.4
            ])
        attributedString.addAttribute(.foregroundColor, value: UIColor(red: 1.0 / 255.0, green: 6.0 / 255.0, blue: 16.0 / 255.0, alpha: 1.0), range: NSRange(location: 0, length: string1.count));
 yourLabel.attributedText = attributedString;
Volkan Sonmez
  • 745
  • 3
  • 14