【问题标题】:Change color of a certain word in UILabel更改 UILabel 中某个单词的颜色
【发布时间】:2017-05-28 10:31:36
【问题描述】:

我只想改变标签字符串中某个单词的颜色。

我想做的是:

我想怎么做:

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

所以我需要一个建议来做这件简单的事情,我需要一个技巧来做这件事。各位可以发一下。

【问题讨论】:

  • 请将您的代码发布为文本,而不是图像。您无法从图像中搜索或引用代码。
  • @maddy 我的错,对不起。

标签: ios swift swift3 uilabel


【解决方案1】:

试试这个,当你尝试获取字符串的范围时,你的属性字符串没有价值。在此之前,您必须为属性字符串提供一个字符串值。你

  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)

或者你可以做一个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
  }

使用它。

      self.testLabel.colorString(text: "mehmet alper tabak",
                           coloredText: "alper")

【讨论】:

  • 谢谢,就是这样。现在我没有问题,我的脑海里还有任何问号^_^
【解决方案2】:

因为myMutableString 在您尝试设置属性时为空,所以超出了范围。试试吧:

let myMutableString = NSMutableAttributedString.init(string: label.text)

【讨论】:

  • 感谢您的回复。有效!但我想知道你还有其他解决方案吗?除了我的方式?
  • 还有什么是静态的,比如“欢迎@username”。在这种情况下,它的长度不会是特殊的。
  • 创建属性字符串let attributedString = NSAttributedString(string: username, attributes: attributed),附加到可变myMutableString.append(attributedString)
  • @JožeWs 如果我想选择一个没有位置和长度的单词该怎么办。我的标签是:“robert plant with queen”,我只想选择“robert plant”并改变它的颜色?
  • 查看我的答案,这是最简单的解决方案
【解决方案3】:

用第一种颜色创建attributedString1

let attributedString1 = NSAttributedString(string: "robert plant ", attributes: [NSForegroundColorAttributeName: color1])

用第二种颜色创建attributedString2

let attributedString1 = NSAttributedString(string: "with queen", attributes: [NSForegroundColorAttributeName: color2])

将它们添加到myMutableString

myMutableString.append(attributedString1)
myMutableString.append(attributedString1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2018-09-22
    • 2013-05-17
    相关资源
    最近更新 更多