1

我有一个基于 TextKit 的编辑器,支持添加图像。我想在单独的行上显示每个图像。

我的代码在我的 NSTextStorage 子类中看起来像这样(谢谢 TextEdit)

- (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;
}

(_isEditing 是一个用于记账的布尔标志)

输出看起来像这样输出 http://take.ms/QCvRK

我在 NSMutableParagraphStyle 上尝试了各种参数,但在每张图片后都无法换行。

在文本附件周围添加换行符 ("\r") 将导致字形错误

  !!! _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

我尝试将NSTextAttachment子类化以覆盖attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex:以便将宽度设置为设备宽度,这导致附加图像看起来被炸毁。

关于如何在每张图片之后立即引入换行符的任何建议?如果我能让文本在图像附件周围流动,那就太好了。

提前致谢。

4

0 回答 0