每一个EmotionView就是一个button,监听点击事件,把该emotionView的emotion属性通过通知发送出去,对每一页表情即GridView添加长按手势,当手势触发时遍历所有子控件,哪一个子控件的frame包含触摸点,然后把该emotionView的emotion属性通过通知发送出去,当接受到通知时判断表情的类型,来判断是插入emoji还是图片表情
emotionViews是GridView存放所有emotionView的数组不包括删除按钮
//长按式检测出在哪个表情范围
-(LSEmotionView*)selectedEmotionView:(CGPoint)point
{
__block LSEmotionView *emotionView=nil;
[self.emotionViews enumerateObjectsUsingBlock:^(LSEmotionView * obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (CGRectContainsPoint(obj.frame, point)) {
emotionView=obj;
*stop=YES;
}
}];
return emotionView;
}
当插入的是emoji时直接调用textView的insertText方法插入,当是图片表情时先获取textView的富文本,同时获取textView的selectdRange,然后在指定位置插入富文本,一个图片需要创建一个NSTextAttachment,为了以后使用,所以这里自定义了LSTextAttachment(包含一个emotion模型),新浪微博发送表情时发送的是文本,所以发送时还需要获取图片表情的描述发送过去。赋值完富文本需要重新设置textView的selectdRange,不设置会跑到最后
-(void)addEmotion:(LSEmotion *)emotion
{
NSInteger index=self.selectedRange.location;
if (emotion.code) {
NSString *str= [NSString emojiWithStringCode:emotion.code];
[self insertText:str];
}else{
NSMutableAttributedString *attributedString=[[NSMutableAttributedString alloc ]initWithAttributedString:self.attributedText];
LSTextAttachment *ata=[[LSTextAttachment alloc]init];
ata.emotion=emotion;
ata.bounds=CGRectMake(0, -4, self.font.lineHeight, self.font.lineHeight);
NSAttributedString *att=[NSAttributedString attributedStringWithAttachment:ata];
[attributedString insertAttributedString:att atIndex:index];
[attributedString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedString.length)];
self.attributedText=attributedString;
self.selectedRange=NSMakeRange(index+1, 0);
}
}
获取真实文本,遍历富文本,判断NSAttaachment是否有值,如果有值则取出对应表情的描述,反之直接取出
-(NSString *)realText
{
NSMutableString *str=[NSMutableString string];
[self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
LSTextAttachment *ata=attrs[@"NSAttachment"];
if (ata) {
[str appendString:ata.emotion.chs];
}else {
NSString *name=[self.attributedText attributedSubstringFromRange:range].string;
[str appendString:name];
}
}];
return str;
}