swift - 如何在 swift 中为 NSAttributedString 使用 replacingOccurrences?

标签 swift string nsattributedstring

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

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

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

我该怎么做?

最佳答案

为了让这个工作,

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))
    }

截图:

enter image description here

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

关于swift - 如何在 swift 中为 NSAttributedString 使用 replacingOccurrences?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355019/

相关文章:

ios - 如何使用 Firestore 中的集合和子集合在数组中创建数组?

ios - 如何识别移动光标上的链接属性范围

ios - 将 NSAttributedString 转换成 Data 进行存储

将字符串转换为 double 或 float 以执行数学方程式

ios - NSAttributedString 添加文本对齐

ios - Swift 中的异步 NSOperation 依赖

ios - SocketIOClient-Swift : Unable to authenticate socket server

ios - 是否有必要在钥匙串(keychain)中为访问组命名

string - 在 Anylogic 中将字符串转换为日期和时间

c - 如何定义字符串数组的结尾