我有一个基于TextKit的编辑器,支持添加图像。我想在不同的行上显示每个图像。
我的代码看起来像这样(谢谢TextEdit),在我的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;
}
(_ isEditing是一个用于记账的布尔标志)
输出看起来像Output 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:,以便将宽度设置为设备宽度,这导致所附的图像看起来很破旧。
关于如何在每张图片后立即引入换行符的任何建议?如果我能让文本在图像附件中流动,那也很棒。
提前致谢。