图文混排——用表情代替 “[文字]”显示

1.简单设置带属性的字符串

    定义一个NSMutableAttributedString带属性的字符串

    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"hello[1_1] world![哈哈][微笑]"];

    设置属性

    [str setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:60], NSForegroundColorAttributeName:[UIColor redColor], NSBackgroundColorAttributeName:[UIColor greenColor], NSUnderlineColorAttributeName:[UIColor blueColor], NSUnderlineStyleAttributeName:@(NSUnderlineStyleDouble)} range:NSMakeRange(0, 5)];

    显示

    _label.attributedText = str;

2. 用表情代替带【】的文字(qq会话,微信会话)

    定义正则表达式

    NSString *pattern = @"\\[[\u4E00-\u9FA5]+\\]";

    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];

    

    NSString *text = @"hello[1_1] world![哈哈]";

    得到符合表达式的数组NSTextCheckingResult类型的

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

    

    定义一个带附件的字符串

    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];

 

    for (NSTextCheckingResult *result in resultArray) {

        位置

        NSRange range = result.range;

        得到附件

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

        设置附件的图片

        attach.image = [UIImage imageNamed:@"d_guzhang"];

        得到附件生成的字符串

        NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attach];

        把文字替换成表情

        [attStr replaceCharactersInRange:range withAttributedString:imageStr];

    }

    _label.attributedText = attStr;

转载于:https://www.cnblogs.com/huoran1120/p/5232302.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值