Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Make UIImageView resize to fit UILabel with AutoLayout

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?

like image 638
el-flor Avatar asked Dec 12 '15 13:12

el-flor


1 Answers

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

like image 168
beyowulf Avatar answered Nov 20 '22 23:11

beyowulf