iOS-富文本之表情文字混排

场景:如微信一样,可以发送emoji表情,以及emoji表情与文字混排。

主要实现依据类:

1.NSMutableAttributedString

将文本转化成NSMutableAttributedString类型,进而可以赋予文字属性

 

2.NSRegularExpression

生成正则表达式规则,查找文本对应的emoji表情符号

 

3.NSTextAttachment

将查找到的emoji表情符号转换成图片

 

4.首先需要创建emoji表情与符号的对应表(NSDictionary)

代码中的正则表达式可根据需要以自行修改,字体属性(大小、颜色)可以根据需要作为接口参数传入

具体代码如下:

/根据对应的map,将含有表情符号的文本转化成表情
+ (NSMutableAttributedString *)convertEmojiTextWithText:(NSString *)text {
    //正则表达式
    NSString *patternStr = @"\\[.{1,2}\\]";
    
    //字体属性
    UIFont *font = [UIFont systemFontOfSize:17];
    NSDictionary *textAttributes = @{NSFontAttributeName: font};
    //字体行高
    CGFloat attachmentHeight = font.lineHeight;
    
    //转化为
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text attributes:textAttributes];
    
    //正则对象
    NSError *err;
    NSRegularExpression *regularExpression = [[NSRegularExpression alloc] initWithPattern:patternStr options:NSRegularExpressionCaseInsensitive error:&err];
    NSArray *matchStrs = [regularExpression matchesInString:text options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, attributeStr.string.length)];
    
    if (matchStrs.count > 0) {
        for (int i = (int)matchStrs.count-1; i >= 0; i --) {
            NSTextCheckingResult *result = matchStrs[i];
            NSRange range = result.range;
            NSString *emojiStr = [text substringWithRange:range];
            if ([EmojiMapModel getImgNameWithText:emojiStr] != nil) {
                NSLog(@"imgname: %@", [[EmojiMapModel getImgNameWithText:emojiStr] stringByAppendingString:@".png"]);
                UIImage *img = [UIImage imageNamed:[[EmojiMapModel getImgNameWithText:emojiStr] stringByAppendingString:@".png"]];
                
                //创建一个NSTextAttachment
                NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
                attachment.image = img;
                CGFloat attachmentWidth = attachmentHeight * img.size.width/ img.size.height;
                attachment.bounds = CGRectMake(0, (font.capHeight-font.lineHeight)/2, attachmentWidth, attachmentHeight);
                
                //生成NSAttributedString
                NSAttributedString *attstr = [NSAttributedString attributedStringWithAttachment:attachment];
                
                //把字符串替换成表情
                [attributeStr replaceCharactersInRange:range withAttributedString:attstr];
            }
        }
    }
    return attributeStr;
}

调用:

如设置 cell的label属性的attributedText,调用上述方法(函数),传入文本内容

cell.textLb.attributedText = [CinUtil convertEmojiTextWithText: model.content];

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值