iOS_NSTextAttachment图文混排,图片和文字对齐

NSTextAttachment

需求:图文混排

初始实现的代码如下:

let label = UILabel()
label.frame = CGRect(x: 50.0, y: 150.0, width: 200.0, height: 100)
label.backgroundColor = .purple
label.numberOfLines = 0
self.view.addSubview(label)

let attributedStr = NSMutableAttributedString()

// 图片
let image: UIImage = UIImage(named: "online") ?? UIImage()
// 图片高度跟文字高度一致
let imageHeight = label.font.lineHeight
// 高度确定后,根据宽高比,算出图片应该显示的高度
let imageWidth = image.size.width * imageHeight / image.size.height

let attach = NSTextAttachment()
attach.image = image
attach.bounds = CGRect(x: 0.0,
                       y: 0.0,
                       width: imageWidth,
                       height: imageHeight)

let imageStr = NSAttributedString(attachment: attach)
attributedStr.append(imageStr)

// 增加图片后与文字间距
let spacingStr = NSAttributedString(string: " ")
attributedStr.append(spacingStr)

// 昵称
let nameStr = NSAttributedString(string: "莫小言:jKf 阿斯利康打火机v爱仕达比爱是妒忌丽丽i就是懒得8级莉莎爱睡觉的就是的i临时冻结i欧路莎几点")
attributedStr.append(nameStr)

label.attributedText = attributedStr

运行结果如下:
在这里插入图片描述
问题:图标没有跟文字对齐(没有处在同一水平线上)


原因:attachment 默认是 显示在 baseline 上方的,所以需要调整一下 attachmentoriginY
修改 bounds 赋值如下,就能解决:

// attachment 默认是 显示在 baseline 上方的
// 为了跟文字对齐,需要将 originY 往上偏移 descender
attach.bounds = CGRect(x: 0.0,
                       y: label.font.descender,
                       width: imageWidth,
                       height: imageHeight)

baselinedescender 的相关知识可以看我这篇文章:iOS_UIFont的Attributes解析

修改后运行效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

莫小言mo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值