iOS 简单图文混排01

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;
}

显示效果



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值