前言
有时候我们的设计图可能需要在文字的前面或者加入图标,为了代码简洁,我们直接使用UILabel来实现。
一、设计图显示如下:
或者
二、实现代码
1、图标在前面
let img = UIImage(named: "refresh L2")
//创建NSTextAttachment对象
let attachment = NSTextAttachment()
//给NSTextAttachment 对象设置图片
attachment.image = img
//设置NSTextAttachment对象的位置 目的是要图片和UILabel的高度一致
let font = FontWithSize(12)
attachment.bounds = CGRect(x: 0, y: 0, width: img?.size.width ?? 0, height: img?.size.height ?? 0)
//给富文本赋值
let attrImage = NSAttributedString(attachment: attachment)
let attrMub = NSMutableAttributedString()
//给可变的富文本对象赋值
let attrStr = NSAttributedString(string: "上次读到" + " ", attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor: UIColorFromRGB("0c0c1c").withAlphaComponent(0.7)])
attrMub.append(attrStr)
attrMub.append(attrImage)
statusLabel.attributedText = attrMub
2、图标在后面
let img = UIImage(named: "mine_xxxx")
//创建NSTextAttachment对象
let attachment = NSTextAttachment()
//给NSTextAttachment 对象设置图片
attachment.image = img
//设置NSTextAttachment对象的位置 目的是要图片和UILabel的高度一致
let font = FontWithSize(12)
attachment.bounds = CGRect(x: 0, y: -2.5, width: img?.size.width ?? 0, height: img?.size.height ?? 0)
//给富文本赋值
let attrImage = NSAttributedString(attachment: attachment)
let attrMub = NSMutableAttributedString()
//给可变的富文本对象赋值
let attrStr = NSAttributedString(string: "哈哈哈哈", attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor: UIColorFromRGB("#FA4646")])
attrMub.append(attrStr)
attrMub.append(attrImage)
statusLabel.attributedText = attrMub
END.