UILabel添加图片之富文本的简单应用

若想对UILabel添加图片,那么就需要使用NSMutableAttributedString来定义
先定义一个普通的label

UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-10, 100)];
lab.numberOfLines = 0;
[self.view addSubview:lab];

然后对其定义

复制代码
//创建富文本
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@"   我纳斯达克市场部撒草卡死你查看售楼处内 按时打算打算的撒打算离开的骄傲是是大神快了解到撒开了就对啦可视对讲卢卡斯的卡洛斯的骄傲"];
//NSTextAttachment可以将要插入的图片作为特殊字符处理
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
//定义图片内容及位置和大小
attch.image = [UIImage imageNamed:@"tab_suning"];
attch.bounds = CGRectMake(0, 0, 61, 14);
//创建带有图片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
复制代码
//将图片放在最后一位
//[attri appendAttributedString:string];
//将图片放在第一位
[attri insertAttributedString:string atIndex:0];
//用label的attributedText属性来使用富文本
lab.attributedText = attri;

然后效果如下

若想对图片添加点击事件,现在的想法是在label上添加一个透明按钮,位置大小跟图片的相同

lab.userInteractionEnabled = YES;
UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
clearBtn.frame = CGRectMake(0, 12, attch.bounds.size.width, attch.bounds.size.height+3);
clearBtn.backgroundColor = [UIColor clearColor];
[clearBtn addTarget:self action:@selector(alertSth) forControlEvents:UIControlEventTouchUpInside];
[lab addSubview:clearBtn];

效果如下

 
posted @   brave-sailor  阅读(178)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示