第一步:外界需要传表情按钮点击时候的数据过来
- (void)publishTextViewWith:(YSWeiBoEmotion *)emotion {
if (emotion.code) {
[self insertText:emotion.code.emoji];// 把emoji表情的16进制编码转为文字
}
else if (emotion.png)// 表情的png图片名
{
// 其实只是使用NSTextAttachment将想要插入的图片作为一个字符处理,转换成NSAttributedString,然后UITextView直接进行渲染就搞定了。上面的代码是初始化一个NSTextAttachment,然后set一下image属性,也可以使用NSTextAttachment的init(data contentData: NSData?, ofType uti: String?)方法来设置图片。
// 转换为NSAttributedString
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:emotion.png];// 获取图片名字
CGFloat attchWH = self.font.lineHeight;
attachment.bounds = CGRectMake(0, -4, attchWH, attchWH);
NSAttributedString *attritedString = [NSAttributedString attributedStringWithAttachment:attachment];
// 插入属性文字到光标位置
[self insertAttributeText:attritedString];//??????
}
}
把NSAttributedString拼接图片
- (void)insertAttributeText:(NSAttributedString *)text
{
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
// 拼接之前的文字(图片和普通文字)
[attributedText appendAttributedString:self.attributedText];
// 拼接图片
NSUInteger loc = self.selectedRange.location;
[attributedText insertAttributedString:text atIndex:loc];
self.attributedText = attributedText;
// 移除光标到表情的后面
self.selectedRange = NSMakeRange(loc + 1, 0);
}
把把emoji表情的16进制编码转为文字
这里定义一个宏
#define EmojiCodeToSymbol(c) ((((0x808080F0 | (c & 0x3F000) >> 4) | (c & 0xFC0) << 10) | (c & 0x1C0000) << 18) | (c & 0x3F) << 24)
+ (NSString *)emojiWithIntCode:(int)intCode {
int symbol = EmojiCodeToSymbol(intCode);
NSString *string = [[NSString alloc] initWithBytes:&symbol length:sizeof(symbol) encoding:NSUTF8StringEncoding];
if (string == nil) {
string = [NSString stringWithFormat:@"%C", (unichar)intCode];
}
return string;
}
- (NSString *)emoji {
return [NSString emojiWithStringCode:[NSString stringWithFormat:@"%@",self]];
}
+ (NSString *)emojiWithStringCode:(NSString *)stringCode {
char *charCode = (char *)stringCode.UTF8String;
int intCode = (int)strtol(charCode, NULL, 16);
return [self emojiWithIntCode:intCode];
}