前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >label 图片替换文字

label 图片替换文字

原创
作者头像
conanma
修改2021-05-11 14:38:17
1.2K0
修改2021-05-11 14:38:17
举报
文章被收录于专栏:正则正则

http://www.jianshu.com/p/99f2950d5a79

NSString * pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";

        NSError *error = nil;

        NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

        if (!re) {

            NSLog(@"%@", [error localizedDescription]);

        }

        NSMutableArray *face = [[EmojiManager share] getAllEmojis];

        //通过正则表达式来匹配字符串

        NSArray *resultArray = [re matchesInString:richText options:0 range:NSMakeRange(0, richText.length)];

        //用来存放字典,字典中存储的是图片和图片对应的位置

        NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:resultArray.count];

        //根据匹配范围来用图片进行相应的替换

        for(NSTextCheckingResult *match in resultArray) {

            //获取数组元素中得到range

            NSRange range = [match range];

            //获取原字符串中对应的值

            NSString *subStr = [richText substringWithRange:range];

            for (int i = 0; i < face.count; i ++)

            {

                EmojiModel *model = face[i];

                if ([model.strcode isEqualToString:subStr])

                {

                    //face[i][@"gif"]就是我们要加载的图片

                    //新建文字附件来存放我们的图片

                    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];

                    //给附件添加图片

                    textAttachment.image = [UIImage imageNamed:model.strpic];

                    //把附件转换成可变字符串,用于替换掉源字符串中的表情文字

                    NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];

                    //把图片和图片对应的位置存入字典中

                    NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];

                    [imageDic setObject:imageStr forKey:@"image"];

                    [imageDic setObject:[NSValue valueWithRange:range] forKey:@"range"];

                    //把字典存入数组中

                    [imageArray addObject:imageDic];

                }

            }

        }

        //从后往前替换

        for (int i = imageArray.count -1; i >= 0; i--)

        {

            NSRange range;

            [imageArray[i][@"range"] getValue:&range];

            //进行替换

            [attributeString replaceCharactersInRange:range withAttributedString:imageArray[i][@"image"]];

        }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档