iOS中匹配表情包

来源:互联网 发布:广告算法工程师面试题 编辑:程序博客网 时间:2024/04/27 14:03

         在如日中天的互联网时代,开发逐渐变的火热,效仿qq和微信的项目也越来越多,那么在这个伟大自由的世界中想自由的发表评论,那么或多或少的会用到自己内心的小情绪(表情),在项目中怎么匹配表情包

1:首先我们需要建立自己需要匹配的lable字段,譬如titlelabel,而且这个字段中又包含文字又含有表情,比如这个文章不错[赞],请给一个笑脸[笑脸]。

2:接下来将tilelabel转换成

可变属性字符串

 NSMutableAttributedString * mAttributedString = [[NSMutableAttributedStringalloc]initWithString:[NSStringstringWithFormat:@"%@",model.Title]];

3:匹配表情,用到表情的正则表达式。

//创建匹配正则表达式的类型描述模板

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

4:创建匹配对象

//创建匹配对象

      NSError * error;

        NSRegularExpression * regularExpression = [NSRegularExpressionregularExpressionWithPattern:patternoptions:NSRegularExpressionCaseInsensitiveerror:&error];

            NSArray * resultArray = [regularExpressionmatchesInString:mAttributedString.stringoptions:NSMatchingReportCompletionrange:NSMakeRange(0, mAttributedString.string.length)];

5:开始遍历标题中所含的表情

 //开始遍历逆序遍历

            for (NSInteger i = resultArray.count -1; i >= 0; i --)

            {

                //获取检查结果,里面有range

                NSTextCheckingResult * result = resultArray[i];

                //根据range获取字符串

                NSString * rangeString = [mAttributedString.stringsubstringWithRange:result.range];

                //获取图片

                UIImage * image = [selfgetImageWithRangeString:rangeString];//这是个自定义的方法

                

                if (image !=nil)

                {

                    //创建附件对象

                    NSTextAttachment * imageTextAttachment = [[NSTextAttachmentalloc]init];

                    //设置图片属性

                    imageTextAttachment.image = image;

                    

                    //根据图片创建属性字符串

                    NSAttributedString * imageAttributeString = [NSAttributedStringattributedStringWithAttachment:imageTextAttachment];

                    //开始替换

                    [mAttributedString replaceCharactersInRange:result.rangewithAttributedString:imageAttributeString];

                    image=nil;

                    imageTextAttachment=nil;

                    imageAttributeString=nil;

                    rangeString=nil;

                }

            }

6.并显示在label上

   //处理完毕后显示在label

  self.titleLabel.attributedText = mAttributedString;

7:上述中调用的方法:

//根据rangeString获取plist中的图片

-(UIImage *)getImageWithRangeString:(NSString *)rangeString

{

    //开始遍历

    for (NSDictionary * tempDictin pictureArray)

    {

        if ([tempDict[@"chs"]isEqualToString:rangeString])

        {

            //获得字典中的图片名

            NSString * imageName = tempDict[@"png"];

            

            //根据图片名获取图片

            UIImage * image = [UIImageimageNamed:imageName];

            

            //返回图片

            return  image;

        }

    }

    

    returnnil;

}

8:根据自己的需要建立需要的plist文件,也可以使用后台接口所给的字段进行解析,格式随意,但是解析方法需要根据情况而改变。


2 0
原创粉丝点击