如何在 Swift 中将 UIImage 嵌入到 UILabel?

How to embed UIImage to UILabel in Swift?

我想制作一个右上角带有小 x 图标的 UILabel(用于照片标签),这样当我点击 x 时,UILabel 就会消失。

我发现这是将图像嵌入 ui 标签的一种方法:

var attachment = NSTextAttachment()
attachment.image = UIImage(named: "rsz_cancel30.png")
var attachmentString = NSAttributedString(attachment: attachment)
var myString = NSMutableAttributedString(string: labelString)
myString.appendAttributedString(attachmentString)
uiLabel.attributedText = myString`

但是,当我尝试使用 uiLabel.sizetoFit() 时,它 "sizes to fit" 图像,因此标签变成了小方块图标的大小,而不是适合 both文本和 ui图像。

与其尝试将图像嵌入 UILabel,不如创建一个包含 UILabel 和 UIImageView 的 UIContainerView。这样,您可以使用自动布局让自动调整大小正常工作,同时仍然能够以编程方式创建视图。

您可以在 Container Views here 上找到优秀的教程。总结一下,试试:

  1. 将容器视图拖到故事板
  2. 为新的 UIViewController
  3. 创建一个新的 class
  4. 将UILabel和UIImageView放入其中,自动布局
  5. 连接 ember segue,自动布局

原来是我傻了

uiLabel.text = labelString

出于某种原因被注释掉了。