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];

 

你可能感兴趣的:(#,iOS开发小结)