如果我将图像添加到字符串,为什么UILabel的宽度错误

时间:2019-11-04 07:35:38

标签: uilabel nsattributedstring nsmutableattributedstring nstextattachment

如果仅使用所有字符串,这没问题

let at = NSMutableAttributedString(string: "")
at.append(NSAttributedString(string: "a"))
at.append(NSAttributedString(string: "b"))
at.append(NSAttributedString(string: "c"))
at.append(NSAttributedString(string: "d"))
at.append(NSAttributedString(string: "e"))

labelName.attributedText = at

enter image description here

如果将图像添加到字符串,则标签的宽度错误

let at = NSMutableAttributedString(string: "")
at.append(NSAttributedString(string: "a"))
at.append(NSAttributedString(string: "b"))
at.append(NSAttributedString(string: "c"))
at.append(NSAttributedString(string: "d"))
at.append(NSAttributedString(string: "e"))

let img = NSTextAttachment()
img.image = UIImage(named: "add")
let imgString = NSAttributedString(attachment: img)
at.append(imgString)

labelName.attributedText = at

enter image description here

我设置了图像尺寸和标签尺寸,但是宽度仍然错误

img.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
labelName.frame.size.width = 1000
labelName.sizeToFit()

如何设置正确的宽度?

0 个答案:

没有答案