【问题标题】:How to use replacingOccurrences for NSAttributedString in swift?如何在 swift 中使用 NSAttributedString 的 replaceOccurrences?
【发布时间】:2018-03-19 02:33:29
【问题描述】:

NSAttributed 类型语句中,我想保留现有的属性值并给它一个新的属性值。

问题在于 replacingOccurrences 仅适用于字符串类型,因为我想在每次单词出现在整个句子中时都给出一个新值。

如果我将NSAttributedString 更改为字符串类型,属性值将被删除。我必须保留现有的价值观。

我该怎么做?

【问题讨论】:

  • 显示你迄今为止尝试过的内容。

标签: swift string nsattributedstring


【解决方案1】:

为了让这个工作,

1. 首先,您需要找到字符串中存在的所有重复子字符串的索引。为此,您可以使用:https://stackoverflow.com/a/40413665/5716829

extension String {
    func indicesOf(string: String) -> [Int] {
        var indices = [Int]()
        var searchStartIndex = self.startIndex

        while searchStartIndex < self.endIndex,
            let range = self.range(of: string, range: searchStartIndex..<self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }

        return indices
    }
}

2.接下来,您需要将所需的属性应用于每个索引处的子字符串,即

    let str = "The problem is that replacingOccurrences Hello is only possible for string types, as I want to give Hello a new value every time Hello the word appears in the entire sentence Hello."
    let indices = str.indicesOf(string: "Hello")
    let attrStr = NSMutableAttributedString(string: str, attributes: [.foregroundColor : UIColor.blue])
    for index in indices
    {
        //You can write your own logic to specify the color for each duplicate. I have used some hardcode indices
        var color: UIColor
        switch index
        {
        case 41:
            color = .orange
        case 100:
            color = .magenta
        case 129:
            color = .green
        default:
            color = .red
        }
        attrStr.addAttribute(.foregroundColor, value: color, range: NSRange(location: index, length: "Hello".count))
    }

截图:

如果您仍然遇到任何问题,请告诉我。快乐编码..?

【讨论】:

  • 41、100 和 129 是我在索引数组中得到的“Hello”的索引。这就是为什么我说我刚刚对它们进行了硬编码以使其正常工作。您可以添加自己的逻辑来为不同的索引添加颜色。
【解决方案2】:

您可以使用replaceCharacters。您可以找到要删除的子字符串的范围并将其用作您的范围。

【讨论】:

  • @allanWay 您可以遍历它,使用每个子字符串的范围,将其替换为属性字符串。
  • 如您所说,如果存在重复文本,您将无法获得想要的效果。
猜你喜欢
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多