简体   繁体   中英

How to embed UIImage to UILabel in Swift?

I want to make a UILabel (for a photo tag) with a small x icon in the top right corner, so that when I hit the x, the UILabel disappears.

I found this is one way to embed the image into the ui label:

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`

However, when I try to use uiLabel.sizetoFit(), it "sizes to fit" the image, so the label becomes the size of the small square icon, instead of fitting both the text and the uiimage.

Turns out I stupidly had the line

uiLabel.text = labelString

commented out for whatever reason.

Rather than trying to embed the image into the UILabel, you should create a UIContainerView that contains a UILabel and UIImageView. This way, you can use Auto Layout to get auto-sizing to work properly while still being able to create the view programmatically.

You can find an excellent tutorial on Container Views here . To sumarize, try:

  1. Drag a Container View to the Storyboard
  2. Create a new class for the new UIViewController
  3. Put the UILabel and UIImageView inside, auto layout
  4. Hook up an ember segue, auto layout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM