首页 > 解决方案 > 无法为多个单词提供单独的颜色

问题描述

我有一个特定的句子。我必须给那句话中的四个单词涂上黑色。

这就是我尝试过的方式......

viewDidLoad,

rangeArray = ["Knowledge","Events","Community","Offers"]

    for text in rangeArray {
      let range = (bottomTextLabel.text! as NSString).range(of: text)

      let attribute = NSMutableAttributedString.init(string: bottomTextLabel.text!)
      attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black , range: range)

      self.bottomTextLabel.attributedText = attribute
    }

但是使用此代码,我只得到黑色的“优惠”一词,而不是所有 4 个单词都为黑色。我究竟做错了什么...?

标签: iosswift

解决方案


在您的代码中,您正在self.bottomTextLabel.attributedText为每次运行更新for loop.

而不是你必须

  1. NSMutableAttributedString使用sentence,创建一个
  2. attributes根据您的rangeArray和添加所有相关的
  3. 然后最后将其设置attrStrattributedText.bottomTextLabel

这就是我想说的,

if let sentence = bottomTextLabel.text {
    let rangeArray = ["Knowledge","Events","Community","Offers"]
    let attrStr = NSMutableAttributedString(string: sentence)
    rangeArray.forEach {
        let range = (sentence as NSString).range(of: $0)
        attrStr.addAttribute(.foregroundColor, value: UIColor.black, range: range)
    }
    self.bottomTextLabel.attributedText = attrStr
}

推荐阅读