图文混排

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

    //定义一个NSMutableAttributedString带属性的字符串
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"hello[1_1] world![哈哈][微笑]"];
    //设置属性
    [str setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:60], NSForegroundColorAttributeName:[UIColor redColor], NSBackgroundColorAttributeName:[UIColor greenColor], NSUnderlineColorAttributeName:[UIColorblueColor], NSUnderlineStyleAttributeName:@(NSUnderlineStyleDouble)} range:NSMakeRange(0, 5)];
    //显示
    _label.attributedText = str;
  1. 用表情代替带【】的文字(qq会话,微信会话)


    //定义正则表达式
    NSString *pattern = @"\\[[\u4E00-\u9FA5]+\\]";
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:patternoptions: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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容