1、在Label中显示图片
// 图文混排显示 - (void)setLabel { // NSTextAttachment - 附件 NSTextAttachment *attachMent = [[NSTextAttachment alloc] init]; // 为附件设置图片 attachMent.image = [UIImage imageNamed: @"d_aini"]; // 键附件添加到图文混排 NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachMent]; // 设置 label 内容 self.label.backgroundColor = [UIColor grayColor]; self.label.attributedText = str; }显示效果
2、设置显示图片尺寸
// 图文混排控制图片大小 - (void)setLabel2 { // NSTextAttachment - 附件 NSTextAttachment *attachMent = [[NSTextAttachment alloc] init]; // 设置图片 attachMent.image = [UIImage imageNamed: @"d_aini"]; // 设置图片大小 // 图片都是正方形,通常跟文字大小差不多 图片大小跟文字高度相同,不是跟Label高度相同 CGFloat height = self.label.font.lineHeight; attachMent.bounds = CGRectMake(0, 0, height, height); // 添加 NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachMent]; // 设置 label 内容 self.label.backgroundColor = [UIColor grayColor]; self.label.attributedText = str; }显示效果
3、文字中插入图片
// 文字图片拼接显示 - (void)setLabel3 { // NSTextAttachment - 附件 // 1.创建文本附件包含图片,知道附件 bounds NSTextAttachment *attachMent = [[NSTextAttachment alloc] init]; // 设置图片 attachMent.image = [UIImage imageNamed: @"d_aini"]; // 设置大小 CGFloat height = self.label.font.lineHeight; attachMent.bounds = CGRectMake(0, 0, height, height); // 添加 // 2.使用附件创建属性字符串 NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:attachMent]; // 拼接文字 NSString *str = @"米"; // 3.创建可变字符 拼接字符串 NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:str]; [strM appendAttributedString:attrString]; [strM appendAttributedString: [[NSAttributedString alloc] initWithString: @"天天"]]; // 设置 label 内容 self.label.backgroundColor = [UIColor grayColor]; self.label.attributedText = strM; }显示效果
时间: 2024-10-12 09:02:31