UILabel图文混排显示图片和文字

时间:2022-03-09 23:49:58
//传入文字 自动图片放在左边文字紧接着后排排布
-(void)setAttrDetailLabelWithTitle:(NSString *)title
{

NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] init];
// 添加表情
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
// 表情图片
UIImage *image =[UIImage imageNamed:@"zp"];
image = [UIImage imageWithCGImage:image.CGImage scale:2 orientation:UIImageOrientationUp];

attch.image = image;

// 设置图片大小 和 微调图片的位置
attch.bounds = CGRectMake(0, -2, image.size.width, image.size.height);

// 创建带有图片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[attri appendAttributedString:string];

[attri appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];

[attri appendAttributedString:[[NSAttributedString alloc] initWithString:title]];

// 用label的attributedText属性来使用富文本
self.despLabel.attributedText = attri;
}