Search code examples
swiftuilabelconstraintsnslayoutconstraint

UILabel has wrong frame. Swift


I added four UILabels inside a cell and it seems that I added all the necessary constraints but I cannot make my labels to have a frame that is equal to its text content. Also setting a height is not an option. The label looks like this (text appears in the center and the frame is big):

enter image description here

And I want it to have like this:

enter image description here

Also, I'm doing everything programmatically so I'm not looking for solution using Interface Builder


Solution

  • If you want the label to be the size of the content, set the Content Hugging Priority to .required:

    label.setContentHuggingPriority(.required, for: .horizontal)
    label.setContentHuggingPriority(.required, for: .vertical)
    

    This will prevent lower priority constraints from stretching your label.