Search code examples
swifttextviewnsattributedstring

swift get range of attribute by index in NSAttributedString


I have a NSAttributedString with 2 attributes

From 0 to 5 {0,5} -> attribute1

from 6 to 10 {6,10} -> attribute2

I use

let attributes = textView.textStorage.attributes(at: 7, longestEffectiveRange: nil, in: NSRange(location: 0, length: textView.textStorage.length))

to get attribute at index 7.

Is possibile have the full range of attribute at index 7?

In my example I should get 6-10

Thanks


Solution

  • Yes you can, using enumerateAttributes provide by NSAttributedString to do that. Means that take all the range of each attribute in your string and find which range contains your index

    Code will be like this

    var index = 7
    
    attributeString.enumerateAttributes(in: NSRange(location: 0, length: attributeString.length), using: {
        _, range, _ in
        // if index in range
        if range.contains(index) {
            print("range: ", range)
            // do your code here
        }
    })