图文混排

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;



效果如下:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容