Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of a certain word in UILabel

I just want to change color of some word in my Label's string.

What I want to do is:

What I want to do is:

How Im trying to do:

But it doesnt work and it says: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'

So I need an advice to do this easy thing, and I need a trick to do this. You guys can send your way.

like image 304
Alper Avatar asked May 28 '17 10:05

Alper


People also ask

How do I change the UILabel text in Swift?

To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.

What is UILabel?

A view that displays one or more lines of informational text.


1 Answers

Try this, your attributed string has no value when you try get the range of the string. You got to give the attributed string a string value before that. You

  let descriptionLabel: UILabel = {

      let label = UILabel()

      // String variable containing the text.
      let fullString = "mehmet alper tabak"

      // Choose wwhat you want to be colored.
      let coloredString = "alper"

      // Get the range of the colored string.
      let rangeOfColoredString = (fullString as NSString).range(of: coloredString)

      // Create the attributedString.
      let attributedString = NSMutableAttributedString(string:fullString)
      attributedString.setAttributes([NSForegroundColorAttributeName: UIColor.red],
                              range: rangeOfColoredString)
      label.attributedText = attributedString
     return label
   }()

   descriptionLabel.frame = CGRect(x: 50, y: 50, width: 140, height: 100)
   self.view.addSubview(descriptionLabel)

Or you can do an extension of UILabel.

  extension UILabel {

      func colorString(text: String?, coloredText: String?, color: UIColor? = .red) {

      let attributedString = NSMutableAttributedString(string: text!)
      let range = (text! as NSString).range(of: coloredText!)
      attributedString.setAttributes([NSForegroundColorAttributeName: color!],
                               range: range)
      self.attributedText = attributedString
  }

To use it.

      self.testLabel.colorString(text: "mehmet alper tabak",
                           coloredText: "alper")
like image 165
Martin Borstrand Avatar answered Oct 19 '22 16:10

Martin Borstrand