NSTextAttachment with text flowing around it

1.3k views Asked by At

I have a TextKit based editor with support to adding images. I want to show each image on separate lines.

My code looks like this (Thank you TextEdit), in my subclass of NSTextStorage

- (void)addImageAssets:(NSArray *)allAssets atRange:(NSRange)range;
{

    NSMutableAttributedString *attachments = [NSMutableAttributedString new];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment = NSTextAlignmentCenter;
    paragraphStyle.lineSpacing = 20.0f;

    for (ALAsset *newAsset in allAssets)
    {
        UIImage *theImage = [UIImage imageWithCGImage:newAsset.aspectRatioThumbnail];

        NSTextAttachment *textAttachment = [NSTextAttachment new];
        textAttachment.image = theImage;

        NSMutableAttributedString *replacementString = [NSMutableAttributedString new];
        [replacementString appendAttributedString:[NSAttributedString attributedStringWithAttachment:textAttachment]];
        [replacementString addAttribute:NSParagraphStyleAttributeName
                                  value:paragraphStyle
                                  range:NSMakeRange(0, [replacementString length])];

        [attachments appendAttributedString:replacementString];
    }

    _isEditing = YES;
    [self beginEditing];

    [_backingStore replaceCharactersInRange:range
                       withAttributedString:attachments];

    [self edited:NSTextStorageEditedAttributes
           range:range changeInLength:allAssets.count];
    [super processEditing];


    [self endEditing];
    _isEditing = NO;
}

(the _isEditing is a boolean flag used for book-keeping)

The output looks like this Output http://take.ms/QCvRK

I have tried various parameters on the NSMutableParagraphStyle but I couldn't get a line break after each image.

Appending a line break ("\r") around the text attachment will result in a glyph error

  !!! _NSLayoutTreeLineFragmentRectForGlyphAtIndex invalid glyph index 1
  !!! _NSGlyphTreeInvalidateGlyphsForCharacterRange invalid char range 1
  !!! _NSGlyphTreeInvalidateGlyphsForCharacterRange character count mismatch
  !!! _NSLayoutTreeLineFragmentRectForGlyphAtIndex invalid glyph index 0
  !!! _NSLayoutTreeLineFragmentRectForGlyphAtIndex invalid glyph index 0
  !!! _NSLayoutTreeLineFragmentUsedRectForGlyphAtIndex invalid glyph index 2147483647

I tried to subclass the NSTextAttachment to over-ride the attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex: so that the width is set to the device width, this resulted in the attached image looking blown up.

Any suggestion on how I can introduce a line break right after each image ? Also it would be great if I can get the text to flow around the image attachments.

Thanks in advance.

0

There are 0 answers