iosuitextviewnstextattachment

Redrawing NSTextAttachments in an UITextView with attributed text


I have a NSTextAttachment subclass with overridden
attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex:
imageForBounds:textContainer:characterIndex:.

I need to redraw the attachment(s) at some point. Calling setNeedsDisplay on the UITextView doesn't work.

Any ideas? I'd like to avoid recreating attachments and/or the attributed string.


Solution

  • You'll want to use one of textView.layoutManager's methods.

    If you just want to update a single attachment, you may find this helper method I wrote helpful:

    - (NSRange)rangeOfAttachment:(NSTextAttachment *)attachment {
        __block NSRange ret;
        [self.textStorage enumerateAttribute:NSAttachmentAttributeName
                                     inRange:NSMakeRange(0, self.textStorage.length)
                                     options:0
                                  usingBlock:^(id value, NSRange range, BOOL *stop) {
                                      if (attachment == value) {
                                          ret = range;
                                          *stop = YES;
                                      }
                                  }];
        return ret;
    }
    

    You can pass the resulting NSRange of this method to the first argument of either of those invalidate methods. For the actualCharacterRange: argument of the second method, I've been passing in NULL without any problems.