富文本AttributedString总结(二)之简单实现图文混排

先声明一段文字用于显示

static NSString * const ImageText = @"如果,感到此时的自己很辛苦,那告诉自己:容易走的都是下坡路。坚持住,因为你正在走上坡路,走过去,你就一定会有进步。如果,你正在埋怨命运不眷顾,开导自己:命,是失败者的借口;运,是成功者的谦词。命运从来都是掌握在自己的手中,埋怨,只是一种懦弱的表现;努力,才是人生的态度。";

向内容的最后插入图片

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:ImageText];

UIImage *image = [UIImage imageNamed:@"emoji"];
NSTextAttachment *attachment = [[NSTextAttachment alloc]init];
attachment.image = image;
attachment.bounds = CGRectMake(0, 0, 30, 30);
NSAttributedString *attrStr1 = [NSAttributedString attributedStringWithAttachment:attachment];
[attrStr appendAttributedString:attrStr1];
self.textView.attributedText = attrStr;

也可实现向指定的位置插入图片,为演示该功能,添加了一个按钮用来点击添加图片,添加的位置为 textView的光标所在位置。

//添加按钮
UIButton *emojiBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
emojiBtn.bounds = CGRectMake(0, 0, 100, 40);
emojiBtn.center = CGPointMake(CGRectGetMidX(self.textView.frame), CGRectGetMaxY(self.textView.frame) + 50);
[emojiBtn setTitle:@"插入表情" forState:UIControlStateNormal];
[emojiBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
[emojiBtn addTarget:self action:@selector(emojiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:emojiBtn];

按钮点击用来在光标位置添加:

- (void)emojiBtnClick:(id)sender
{
    //获取textView的富文本,并转换成可变类型
    NSMutableAttributedString *mutaAttrStr = [self.textView.attributedText mutableCopy];
    //获取光标的位置
    NSRange range = self.textView.selectedRange;
    //    NSLog(@"%lu %lu",(unsigned long)range.location,(unsigned long)range.length);
    //声明表情资源 NSTextAttachment类型
    UIImage *image = [UIImage imageNamed:@"emoji"];
    NSTextAttachment *attachment = [[NSTextAttachment alloc]init];
    attachment.image = image;
    attachment.bounds = CGRectMake(0, 0, 30, 30);
    NSAttributedString *attrStr = [NSAttributedString     attributedStringWithAttachment:attachment];
    [mutaAttrStr insertAttributedString:attrStr atIndex:range.location];
    self.textView.attributedText = mutaAttrStr;
}

这样就实现了简单的图文混排,不过我们会发现图片和字体显示的不一致,接下来我们就来解决这个问题,使我们可以根据文字的大小来改变图片的大小。
解决方案:重载了 NSTextAttachment,NSTextAttachment 实现了 NSTextAttachmentContainer,可以给我们改变返回的图像的大小。
重载代码:

//.h
#import 
@interface YOETextAttachment : NSTextAttachment

@end

//.m
#import "YOETextAttachment.h"

@implementation YOETextAttachment

//重载此方法 使得图片的大小和行高是一样的。
- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex
{
    return CGRectMake(0, 0, lineFrag.size.height, lineFrag.size.height);
}

@end

接下来只需要将NSTextAtttachment 替换为 YOETextAttachm

你可能感兴趣的:(富文本AttributedString总结(二)之简单实现图文混排)