【iOS开发】emoji表情的输入思路

时间:2022-09-16 05:31:14

1.自定义一个表情包类继承NSTextAttachment

 #import <UIKit/UIKit.h>

 /** 表情包的自定义类*/
@interface EmojiTextAttach : NSTextAttachment @property (nonatomic,assign) NSRange range; /** 绑定NSTextAttachment所表示的表情和与其对应的标志*/
@property (nonatomic, copy) NSString *emojiTag; /** 表情名称*/
@property (nonatomic, copy) NSString *emojiName; @end

2.每个emoji表情其实就是一张图片,并且每张图片都有统一的编号,也就是说一个emoji

【iOS开发】emoji表情的输入思路

3.将emoji的图片赋值给自定义的表情包类image属性,并且将emoji转为富文本

 #pragma mark - 选择了emoji表情
-(void)emojiView:(FacialView *)emojiView didSelectEmoji:(NSString *)emoji withEmojiPng:(UIImage *)emojiPng
{
EmojiTextAttach *emojiAttch = [[EmojiTextAttach alloc] init];
emojiAttch.image = emojiPng;
emojiAttch.emojiTag = emoji;
// 当前插入的富文本
NSAttributedString *addEmoji = [NSAttributedString attributedStringWithAttachment:emojiAttch]; // 输入框所有的可变富文本
NSMutableAttributedString *allText = [[NSMutableAttributedString alloc] initWithAttributedString:_textView.attributedText];
NSLog(@"allText-->%@",allText); // 将选择的表情插入到输入框
[allText insertAttributedString:addEmoji atIndex:_textView.selectedRange.location]; [allText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18.0] range:NSMakeRange(, allText.length)]; _textView.attributedText = allText; NSLog(@"allText-->%@",allText);
//光标位置
_textView.selectedRange = NSMakeRange(_textView.selectedRange.location + , ); //[_textView setText:[_textView.text stringByAppendingString:emoji]]; [self textViewDidChange:_textView];
}

4.发送时将富文本转为对应图片编号的纯文本发送给服务器

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{ if ([text hasSuffix:@"@"]) { //输入过程 if ([self.delegate respondsToSelector:@selector(showGroupMemberVC)]) {
[self.delegate showGroupMemberVC];
}
} if (_chatAuth) {
if ([_chatAuth isEqual:@"noAuth"]) { [ErrorMessage showErrorMessage:@"您暂时没有发言权限!" inView:[UIApplication sharedApplication].keyWindow];
return NO;
}else if ([_chatAuth isEqual:@"isSaid"]) {
//[ErrorMessage showErrorMessage:@"您今天已经发过言了,明天再来吧!" inView:[UIApplication sharedApplication].keyWindow];
//return NO;
}else{ }
} // 得到纯文本发送
NSString *attrStr = textView.attributedText.getPlainString; if (![attrStr isEqual:@""]) {
if ([text isEqual:@"\n"]) { NSString * headerData = [CommonTool removeHeaderOrTrailSpaceWithContent:attrStr]; if ([self messageLengthToolong:headerData]) {
[ErrorMessage showErrorMessage:@"消息内容过长!" inView:_superView];
return NO;
} if (![headerData isEqual:@""]) {
if ([self.delegate respondsToSelector:@selector(sendMessage:)]) {
[self.delegate sendMessage:headerData];
}
}else{
[ErrorMessage showErrorMessage:@"消息不能为空!" inView:_superView];
} textView.text = @"";
[self recoverInputTextViewFrame:textView]; return NO;
}
}
return YES;
}