我想在 UITextView 中插入图像,所以我使用 textkit 和 NSTextAttachment。但是当我插入图片时,图片显示在 UITextView 内容的上方,效果如下:
代码是这样的:
//
// 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