Search code examples
uitableviewuilabeluitableviewautomaticdimension

Setting label's width and height according to the text length within a UITableViewCell using UITableViewAutomaticDimension


I need a UITableView with cells like this: enter image description here I tried and ended up in this: enter image description here

I used UITableViewAutomaticDimension with Autolayout (pinning the label to 4 sides of the superview and not giving a height constraint) and was able to give dynamic height to the cells. But what I also want is the width of the label to be adjusted according to the size of the text (see first image).

Any help would be highly appreciated. Thanks.


Solution

  • For that all you need to add flexible constraint that adjust according to message label.

    enter image description here

    Give message label trailing to Main SuperView (ContentView) in Greater than or equal to (>=) let say 20 pixels (so it's basically means always maintain that margin of 20 pixels space so it can go more then 20 pixels but not less then that). now you can give trailing of your ChatView to Message label let say 20 pixels.

    also add tailing margin of 20 pixels as in Greater than or equal to (>=) Date label so when the message get very small your background view of message label will not go inside of date.

    enter image description here

    enter image description here