iOS之文本首尾添加图片

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

- (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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容