0

I want to insert image in UITextView, so I use textkit and NSTextAttachment. But when I insert image, the image display above the content in UITextView, the effect like below: enter image description here

and the code is like this:

//
//  TextKitView.m
//  TextKit
//
//  Copyright (c) 2015 icell.com. All rights reserved.
//

#import "SNArticleView.h"

@interface SNArticleImageAttachment : NSTextAttachment

@end

@implementation SNArticleImageAttachment

- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex {

    CGFloat attachmentWidth = CGRectGetWidth(lineFrag) - textContainer.lineFragmentPadding * 2;
    return CGRectMake(0, 0, attachmentWidth, attachmentWidth / self.image.size.width * self.image.size.height);
}



@end



@interface SNArticleView ()

@property (strong, nonatomic) NSTextStorage *textStorage;
@property (strong, nonatomic) UITextView *textView;

@end

@implementation SNArticleView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    _textStorage = [[NSTextStorage alloc] init];

    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [_textStorage addLayoutManager:layoutManager];

    NSTextContainer *textContainer = [[NSTextContainer alloc] init];
    [layoutManager addTextContainer:textContainer];

    _textView = [[UITextView alloc] initWithFrame:self.bounds textContainer:textContainer];
    [_textView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
    [_textView.textContainer setLineFragmentPadding:20];
    [self addSubview:_textView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.textView setFrame:self.bounds];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    _attributedText = [attributedText copy];
    [_textStorage insertAttributedString:_attributedText atIndex:0];
}

- (void)insertImage:(UIImage *)image atLocation:(NSUInteger)index; {
    NSMutableAttributedString *attributedTemp = [self.attributedText mutableCopy];

    SNArticleImageAttachment *attachment = [[SNArticleImageAttachment alloc] init];
    [attachment setImage:image];
    NSAttributedString *imageAttrStr = [NSAttributedString attributedStringWithAttachment:attachment];
    [attributedTemp insertAttributedString:imageAttrStr atIndex:_attributedText.length];

    [_textStorage replaceCharactersInRange:NSMakeRange(0, _attributedText.length) withAttributedString:attributedTemp];

}

@end
lixiaoyu
  • 380
  • 4
  • 18

1 Answers1

1

Finally, I find the solution by myself. Because the NSAttributedString I used had a attribute of paragraph style, and I set the MaximumLineHeight before, so it effected the NSTextAttachment.

lixiaoyu
  • 380
  • 4
  • 18