在 NSMutableAttributedString 中查找子字符串的 Rang 数组

问题描述 投票:0回答:1

我有一个带有 $ 符号的属性字符串,如下所示“价格 1 $ 25 价格 2 美元 价格 3 $" 我想找到 "$"

的所有范围
let attrString = NSMutableAttributedString(string: " price 1 $ 25 \n price 2 $\n price 3 $")
let ranges = // all ranges for $ sign

我需要为“$”设置不同的颜色。

我知道如何在属性字符串中查找范围。

extension NSAttributedString {
func rangeOf(string: String) -> Range<String.Index>? {
    return self.string.range(of: string)
}}

我想知道如何在给定的属性字符串中找到“$”符号范围的数组?

swift nsattributedstring
1个回答
1
投票

往返

AttributedString
非常方便:

let attrString = NSMutableAttributedString(string: " price 1 $ 25 \n price 2 $\n price 3 $")

let attributedString = AttributedString(attrString)
let substring = "$"

// Iterating through all the occurrences of `substring`.
for range in attributedString.characters.ranges(of: substring) {
   // Do something with the current range
   attributedString[range].foregroundColor = .red
}

let response = NSAttributedString(attributedString)
© www.soinside.com 2019 - 2024. All rights reserved.