6.数据准备工作完成,下面开始遍历资源文件找到文字对应的图片,找到后把图片名存入字典中,图片在源字符串中的位置也要存入到字典中,后把字典存入可变数组中。代码如下:
1     //用来存放字典,字典中存储的是图片和图片对应的位置
2     NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:resultArray.count];
3
4     //根据匹配范围来用图片进行相应的替换
5     for(NSTextCheckingResult *match in resultArray) {
6         //获取数组元素中得到range
7         NSRange range = [match range];
8
9         //获取原字符串中对应的值
10         NSString *subStr = [str substringWithRange:range];
11
12         for (int i = 0; i < face.count; i ++)
13         {
14             if ([face[i][@"chs"] isEqualToString:subStr])
15             {
16
17                 //face[i][@"gif"]是我们要加载的图片
18                 //新建文字附件来存放我们的图片
19                 NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
20
21                 //给附件添加图片
22                 textAttachment.image = [UIImage imageNamed:face[i][@"png"]];
23
24                 //把附件转换成可变字符串,用于替换掉源字符串中的表情文字
25                 NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
26
27                 //把图片和图片对应的位置存入字典中
28                 NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];
29                 [imageDic setObject:imageStr forKey:@"image"];
30                 [imageDic setObject:[NSValue valueWithRange:range] forKey:@"range"];
31
32                 //把字典存入数组中
33                 [imageArray addObject:imageDic];
34
35             }
36         }
37     }
  7.转换完成,我们需要对attributeString进行替换,替换的时候要从后往前替换,弱从前往后替换,会造成range和图片要放的位置不匹配的问题。替换代码如下:
1     //从后往前替换
2     for (int i = imageArray.count -1; i >= 0; i--)
3     {
4         NSRange range;
5         [imageArray[i][@"range"] getValue:&range];
6         //进行替换
7         [attributeString replaceCharactersInRange:range withAttributedString:imageArray[i][@"image"]];
8
9     }
  8.把替换好的可变属性字符串赋给TextView
  1     //把替换后的值赋给我们的TextView
  2     self.myTextView.attributedText = attributeString;
  9.替换前后效果如下: