我有一个带有 $ 符号的属性字符串,如下所示“价格 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)
}}
我想知道如何在给定的属性字符串中找到“$”符号范围的数组?
往返
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)