0

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.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
noobprogrammer
  • 345
  • 1
  • 6
  • 20

2 Answers2

0

Turns out I stupidly had the line

uiLabel.text = labelString

commented out for whatever reason.

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
noobprogrammer
  • 345
  • 1
  • 6
  • 20
-1

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
Community
  • 1
  • 1
BradzTech
  • 2,755
  • 1
  • 16
  • 21