• 图文混排——用表情代替"[文字]"


    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;

     
  • 相关阅读:
    __weak
    c++界面设计皮肤工具
    执行游戏时出现0xc000007b错误的解决方法
    2.4.1-Java语言基础(常量)
    句法模式识别(一)-串文法
    一步一步写算法(之hash表)
    LaTeX新人教程,30分钟从全然陌生到基本入门
    初次当面试官的经历和感触
    Android入门第八篇之GridView(九宫图)
    Android-Cannot merge new index 66195 into a non-jumbo instruction的解决的方法
  • 原文地址:https://www.cnblogs.com/damonWq/p/5342767.html
Copyright © 2020-2023  润新知