NSTextAttachment实现图文混排

2023-11-01

苹果在iOS7中推出了一个新的类NSTextAttachment,它是做图文混排的利器,本文就是用这个类,只用50行代码实现文字与表情混排,当然也可以实现段落中的图文混排。
首先说一下文字和表情的混排:
先来做点儿准备工作,搞一个存放表情信息的plist文件
这里写图片描述

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Image" ofType:@"plist"];
    NSArray *face = [NSArray arrayWithContentsOfFile:filePath];

    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
    NSString *regex_emoji =@"\\[[a-zA-Z0-9\\/\\u4e00-\\u9fa5]+\\]";//匹配表情

    NSError *error =nil;

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

    if(!re) {

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

    }

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

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

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

    for(NSTextCheckingResult *match in resultArray) {

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

        NSRange range = [match range];

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

        NSString *subStr = [text substringWithRange:range];

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

            if([face[i][@"cht"] isEqualToString:subStr]) {

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

                //新建文字附件来存放我们的图片,iOS7才新加的对象

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

                //给附件添加图片

                textAttachment.image= [UIImage imageNamed:face[i][@"png"]];

                //调整一下图片的位置,如果你的图片偏上或者偏下,调整一下bounds的y值即可

                textAttachment.bounds=CGRectMake(0, -8, textAttachment.image.size.width, textAttachment.image.size.height);

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

                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];

            }

        }

    }

    //4、从后往前替换,否则会引起位置问题

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

        NSRange range;

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

        //进行替换
        [attributeString replaceCharactersInRange:range withAttributedString:imageArray[i][@"image"]];
    }

以上代码段是写了一个工具类以实现图文混排,也可以为NSString写一个分类来实现。下面说一下用法:

NSString *content =@"文字加上表情[得意][][呲牙]";

NSMutableAttributedString *attrStr = [Utility emotionStrWithString:content];

_contentLabel.attributedText= attrStr;

有了上面的方法,要实现图片和文字的排布就更容易了,只需要将某些图片给它设置一个固定的字符对应即可。
具体方法如下:
NSString *praiseStr =@”路人甲、路人乙”;

NSString *praiseInfo = [NSString stringWithFormat:@”<点赞> %@”,praiseStr];

NSDictionary *attributesForAll =@{NSFontAttributeName:[UIFont systemFontOfSize:14.0],NSForegroundColorAttributeName:[UIColorgrayColor]};

NSMutableAttributedString*attrStr = [Utility exchangeString:@”<点赞>”withText:praiseInfoimageName:@”dynamic_love_blue”];

有什么不足或者bug欢迎及时沟通!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NSTextAttachment实现图文混排 的相关文章

  • mysql数据表查询操作

    数据表查询操作 准备工作 导入之前需要先创建一个数据库 数据库资料传送门 使用新创建的数据库 使用 source 文件地址 导入数据 create database db charset utf8 use db source home py

随机推荐