开发中有时会遇到文本首尾添加图片或者表情的需求,直接上代码:
- (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
网友评论