5
votes

I'm having this issue since quite some time now and it's driving me crazy: I have a UILabel with text that can be dynamically changed, and I have a UIImageView that should act as the text's background. I would like the UIImageView to resize itself to always fit the UILabel's text.

enter image description here

"Paid" could become "Free", or "Payant" in French for instance, and the box behind should always resize.

Using Storyboard, I have tried adding a UIImageView with the UILabel on top of it, and setting the constraints of the UILabel to the UIImageView, but this ends up resizing the UILabel to the UIImageView's size. I cannot set a fixed width or height for the UIImageView because it should adapt.

My second try was to make a UIView, recategorize it as a UIIimageView, add the UILabel as a subview, make the UIView resize to the UILabel and add the image programatically but once again, no success.

What is the right way to do this?

1
With the first method did you try changing the Content Hugging Priority horizontal and vertical to required?beyowulf
You could also just use a UIButton and set it's background image and turn user interactions off.beyowulf
@beyowulf I have tried to UIButton too: the default image is bigger than the text and the button takes the size of the image, and just puts the text in the middle. It doesn't resize to the text. For the first method: I'm not exactly sure how to set up the right constraints with the hugging priority?el-flor

1 Answers

11
votes

For the first method, I assume you set the had the label and the image view have the same vertical and horizontal centers as well has the same height and width. The problem is the layout engine is assume the intrinsic size of the image is more important than the label. To change that you need to change hugging priority and the compression resistance of the views.enter image description here Go to the size inspect of the label (picture) and increase the hugging priority to required. This will for it's height and width to be it's intrinsic height and width. You could also decrease the image view's compression resistance, so it is more amendable to being sized down.

The constraints for the label:enter image description here

You can change the top and leading to place it in the appropriate spot in the view.

The constraints for the image view: enter image description here