在如日中天的互联网时代,开发逐渐变的火热,效仿qq和微信的项目也越来越多,那么在这个伟大自由的世界中想自由的发表评论,那么或多或少的会用到自己内心的小情绪(表情),在项目中怎么匹配表情包
1:首先我们需要建立自己需要匹配的lable字段,譬如titlelabel,而且这个字段中又包含文字又含有表情,比如这个文章不错[赞],请给一个笑脸[笑脸]。
2:接下来将tilelabel转换成
可变属性字符串
NSMutableAttributedString * mAttributedString = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",model.Title]];
3:匹配表情,用到表情的正则表达式。//创建匹配正则表达式的类型描述模板
NSString * pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
4:创建匹配对象
//创建匹配对象
NSError * error;
NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
//开始遍历 逆序遍历
for (NSInteger i = resultArray.count - 1; i >= 0; i --)
{
//获取检查结果,里面有range
NSTextCheckingResult * result = resultArray[i];
//根据range获取字符串
NSString * rangeString = [mAttributedString.string substringWithRange:result.range];
//获取图片
UIImage * image = [self getImageWithRangeString:rangeString];//这是个自定义的方法
if (image != nil)
{
//创建附件对象
NSTextAttachment * imageTextAttachment = [[NSTextAttachment alloc]init];
//设置图片属性
imageTextAttachment.image = image;
//根据图片创建属性字符串
NSAttributedString * imageAttributeString = [NSAttributedString attributedStringWithAttachment:imageTextAttachment];
//开始替换
[mAttributedString replaceCharactersInRange:result.range withAttributedString:imageAttributeString];
image=nil;
imageTextAttachment=nil;
imageAttributeString=nil;
rangeString=nil;
}
}
//处理完毕后显示在label上
self.titleLabel.attributedText = mAttributedString;
7:上述中调用的方法://根据rangeString获取plist中的图片
-(UIImage *)getImageWithRangeString:(NSString *)rangeString
{
//开始遍历
for (NSDictionary * tempDict in pictureArray)
{
if ([tempDict[@"chs"] isEqualToString:rangeString])
{
//获得字典中的图片名
NSString * imageName = tempDict[@"png"];
//根据图片名获取图片
UIImage * image = [UIImage imageNamed:imageName];
//返回图片
return image;
}
}
return nil;
}
8:根据自己的需要建立需要的plist文件,也可以使用后台接口所给的字段进行解析,格式随意,但是解析方法需要根据情况而改变。