美文网首页
iOS之文本首尾添加图片

iOS之文本首尾添加图片

作者: zwing | 来源:发表于2019-11-29 16:04 被阅读0次

    开发中有时会遇到文本首尾添加图片或者表情的需求,直接上代码:

    - (NSAttributedString *)attachHeadImage:(UIImage *)headImage footImage:(UIImage *)footImage targatStr:(NSString *)targatStr {
        // 1.创建富文本
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:targatStr];
        
        // 2.创建NSTextAttachment:做图文混排的利器
        NSTextAttachment *headAttchment = [NSTextAttachment new];
        headAttchment.image = headImage;
        headAttchment.bounds = CGRectMake(0, 0, 15, 15);
        
        NSTextAttachment *footAttchment = [NSTextAttachment new];
        footAttchment.image = footImage;
        footAttchment.bounds = CGRectMake(0, 0, 15, 15);
        
        // 3.将NSTextAttachment转化为NSAttributedString
        NSAttributedString *headImageString = [NSAttributedString attributedStringWithAttachment:headAttchment];
        NSAttributedString *footImageString = [NSAttributedString attributedStringWithAttachment:footAttchment];
        
        // 4.拼接字符串
        [attributedStr insertAttributedString:headImageString atIndex:0];
        [attributedStr appendAttributedString:footImageString];
     
        return attributedStr;
    }
    

    效果图:

    星星.png

    相关文章

      网友评论

          本文标题:iOS之文本首尾添加图片

          本文链接:https://www.haomeiwen.com/subject/cxhgwctx.html