IOS开发之显示微博表情
|
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 }
|
|
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 }
|
