先聲明一段文字用于顯示
static NSString * const ImageText = @"如果萧福,感到此時(shí)的自己很辛苦拉鹃,那告訴自己:容易走的都是下坡路。堅(jiān)持住鲫忍,因?yàn)槟阏谧呱掀侣犯嘌啵哌^(guò)去,你就一定會(huì)有進(jìn)步悟民。如果坝辫,你正在埋怨命運(yùn)不眷顧,開(kāi)導(dǎo)自己:命射亏,是失敗者的借口近忙;運(yùn)竭业,是成功者的謙詞。命運(yùn)從來(lái)都是掌握在自己的手中及舍,埋怨未辆,只是一種懦弱的表現(xiàn);努力锯玛,才是人生的態(tài)度咐柜。";
向內(nèi)容的最后插入圖片
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;
也可實(shí)現(xiàn)向指定的位置插入圖片,為演示該功能更振,添加了一個(gè)按鈕用來(lái)點(diǎn)擊添加圖片炕桨,添加的位置為 textView的光標(biāo)所在位置。
//添加按鈕
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];
按鈕點(diǎn)擊用來(lái)在光標(biāo)位置添加:
- (void)emojiBtnClick:(id)sender
{
//獲取textView的富文本,并轉(zhuǎn)換成可變類(lèi)型
NSMutableAttributedString *mutaAttrStr = [self.textView.attributedText mutableCopy];
//獲取光標(biāo)的位置
NSRange range = self.textView.selectedRange;
// NSLog(@"%lu %lu",(unsigned long)range.location,(unsigned long)range.length);
//聲明表情資源 NSTextAttachment類(lèi)型
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;
}
這樣就實(shí)現(xiàn)了簡(jiǎn)單的圖文混排肯腕,不過(guò)我們會(huì)發(fā)現(xiàn)圖片和字體顯示的不一致献宫,接下來(lái)我們就來(lái)解決這個(gè)問(wèn)題,使我們可以根據(jù)文字的大小來(lái)改變圖片的大小实撒。
解決方案:重載了 NSTextAttachment姊途,NSTextAttachment 實(shí)現(xiàn)了 NSTextAttachmentContainer,可以給我們改變返回的圖像的大小知态。
重載代碼:
//.h
#import <UIKit/UIKit.h>
@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
接下來(lái)只需要將NSTextAtttachment 替換為 YOETextAttachm