如何在swift中使用NSAttribute字符串的replacingOccurrences?

如何在swift中使用NSAttribute字符串的replacingOccurrences?,swift,string,nsattributedstring,Swift,String,Nsattributedstring,在NSAttributedtype语句中,我希望保留现有的属性值,并给它一个新的属性值 问题是,replacingOccurrences仅适用于字符串类型,因为我希望每次单词出现在整个句子中时都给出一个新值 如果我将NSAttributedString更改为字符串类型,则属性值将被删除。我必须保留现有的价值观 我该怎么做呢?你可以用。您可以找到要删除的子字符串的范围,并将其用作您的范围。要使其正常工作 1。首先需要找到字符串中存在的所有重复子字符串的索引。要实现这一点,您可以使用以下方法: 屏幕

NSAttributed
type语句中,我希望保留现有的属性值,并给它一个新的属性值

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

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

我该怎么做呢?

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

要使其正常工作

1。首先需要找到字符串中存在的所有重复子字符串的索引。要实现这一点,您可以使用以下方法:

屏幕截图:


如果你还面临任何问题,请告诉我。Happy Coding..@allanWay您可以对其进行迭代,使用每个子字符串的下一个子字符串的范围,将其替换为属性字符串。正如您所说,如果存在重复文本,则无法获得所需的效果。显示您迄今为止所做的尝试。41、100和129是我在索引数组中获得的“Hello”的索引。这就是为什么我说我刚刚硬编码了他们,让它工作。您可以添加自己的逻辑,为不同的索引添加颜色。
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
    }
}
    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))
    }