0

Is there a way to find all ranges of occurrences of a specific attribute? For example if an attributed string has several ranges with NSBackgroundColorAttributeName set, the function to return the ranges for this occurrences.

Ivaylo Nikolov
  • 501
  • 4
  • 13
  • `enumerateAttribute:inRange:options:usingBlock:` should do the work. In the block, check the value and add it into a `__block NSMutableArray *ranges = [[NSMutableArray alloc] init];` that was created before hand. – Larme Oct 19 '16 at 10:08
  • I was thinking for something like: `var effectiveRange: NSRange = NSRange() if let _ = attributedString.attribute(NSBackgroundColorAttributeName, at: 0, effectiveRange: &effectiveRange){ print("we have a match - should check effectiveRange" }` – Ivaylo Nikolov Oct 20 '16 at 11:40
  • That may works too, but if you have a gap between two NSBackgroundColorAttribute, it would find only if there is one at index 0. You can see http://stackoverflow.com/questions/29152660/extract-uiimage-from-nsattributed-string/29153172#29153172 how to use my previous answer (in Objective-C, but should be easily translated into Swift) – Larme Oct 20 '16 at 11:44
  • Yep - you are correct. anyway my case may be better - I did not explained myself regarding the exact situation, that I need this solution for. Actually I'm iterrating through a NSTextStorage object. And there is `var attributeRuns: [NSTextStorage] { get set }` which gives me the opportunity to enumerate through all attribute runs, grouped by common settings. Tricky, isn't it ;-) – Ivaylo Nikolov Oct 20 '16 at 13:56

0 Answers0