新浪微博-表情键盘的事件处理

每一个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;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值