Search code examples
swiftxcodeuilabel

Dynamically label width with a label background color


I have a label in my TableView Cell and trying to autofit it to the size of the content. It works, but when I add a background color, I see what's wrong here. In my cell, I have a top, left, bottom and right constraint, as you can see in the picture.

How can I adjust the label size to the content?

Edit: I also have this:

override func awakeFromNib() {
    super.awakeFromNib()

    labelChatMessage.sizeToFit()
    labelChatMessage.layoutIfNeeded()

    // Initialization code
}

enter image description here


Solution

  • I have also tried this UI in one of my project.

    Try doing this if it serves your purpose:

    • Select the Leading constraint (Left one)

    • Select "Show the Size Inspector"

    • Change the relation of the constraint to "Greater than or equal"

    enter image description here

    • Your constraint and UI in storyboard will look like this:

    enter image description here

    • And you will get the UI as :

    enter image description here

    I think this is not required in this scenario then:

    labelChatMessage.sizeToFit()
    labelChatMessage.layoutIfNeeded()
    

    because I got the output UI without that.