图文混排

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 50)];

lbl.backgroundColor = [UIColor lightGrayColor];

[self.view addSubview:lbl];



// 0、创建一个空的可变属性字符串

NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] init];


// 1、创建一个属性字符串

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];

attachment.image = [UIImage imageNamed:@"d_aini"];

// 调整图片位置

attachment.bounds = CGRectMake(0, -4, lbl.font.lineHeight, lbl.font.lineHeight);


// 2、根据附件创建属性字符串

NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachment];


// 3、创建文字属性字符串

NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:@"小码哥"];


// 4、创建文件属性字符串

NSAttributedString *str2 = [[NSAttributedString alloc] initWithString:@"爱你"];


// 5、拼接变属性字符串

[strM appendAttributedString:str1];

[strM appendAttributedString:str];

[strM appendAttributedString:str2];


// 6、给lbl赋值,图文混排

lbl.attributedText = strM;



效果如下:


图文混排_第1张图片

你可能感兴趣的:(图文混排)