更改UILabel中某个单词的颜色

Alp*_*per 2 uilabel ios swift swift3

我只是想改变Label的字符串中某些单词的颜色.

我想做的是:

我想做的是:

我是怎么做的:

但它不起作用,它说:'NSMutableRLEArray replaceObjectsInRange:withObject:length :: Out of bounds'

所以我需要一个建议来做这个简单的事情,我需要一个技巧来做到这一点.你们可以发送你的方式.

小智 7

试试这个,当你尝试获取字符串的范围时,你的属性字符串没有值.在此之前,您必须为属性字符串赋予字符串值.您

  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)
Run Code Online (Sandbox Code Playgroud)

或者你可以扩展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
  }
Run Code Online (Sandbox Code Playgroud)

使用它.

      self.testLabel.colorString(text: "mehmet alper tabak",
                           coloredText: "alper")
Run Code Online (Sandbox Code Playgroud)