1

I have a attributed string with $ sign like this " price 1 $ 25 \n price 2 $\n price 3 $" I want find all the ranges of "$"

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

I need to set different color for "$".

I know how to find range in attributed string.

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

I am wondering how I can find an array of ranges of "$" sign in a given attributed string?

WAHID MARUF
  • 51
  • 1
  • 8

1 Answers1

1

Quite easy with a roundtrip to 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)
Bogdan Farca
  • 3,856
  • 26
  • 38