Search code examples
swifttableviewcell

TableView calculates wrong height for dynamic width&height label


I've read multiple threads about this but I've found no solution yet.

I'm making a chat-like application


The app has a TableView that has dynamic height cells in it.

A cell consists of a view and a multiline label in it.

If the label has more characters than >250 it gets shortened with an ending "... see more"


Now the problem is that sometimes the label gets cut off.

I played a little with the Line Break setting of the label, and after changing it to Character Wrap the label shows its full text.

Left picture: Character Wrap - - - Right picture: Word Wrap (I need this)

enter image description hereAs you see on the right picture, the "Bt... See More" gets cut off..


I realised that if I set the label's width or the view's width to a fixed size then the problem gets solved: So maybe the problem's root is in the bubble view's leading constraint:

Align leading to Superview
Constant: 0
Priority: 1000
Multiplier: 0.25

(This is needed so that the bubble view expands maximum to 75% of the superview)

I made a GitHub repo for this:

https://github.com/krptia/chatBubbleTest

Help please!


Anyone?


Solution

  • SOLUTION

    I figured out that if I set the bubble view's leading constant the following:

    Align leading to Superview
    Constant: 0
    Priority: 1000
    Multiplier: 0.25
    

    In order to set the maximum width to 75%, the label inside wraps incorrectly.

    SO I deletet the leading constraint and instead of that I maximize the width via aspect-ratio!

    If I use aspect-ratio 2:3

    Then I achieve the same outcome, but with the label wrapping correctly!!

    Yay

    SOLUTION 2.0

    Okay, now I have figured out that the bubble view's leading constraint's second item (SuperView.Trailing) was Relative to Margin

    After unchecking it, the problem gets fixed, so I don't have to use aspect ratio! Yay

    BUT PAY ATTENTION

    Because using Line Break: Word Wrap also causes some problems.

    Sometimes it tries to break the text into a new line (minimum 2 words) but if the cell was reused then the app might calculate wrong height for the view.


    First picture: Word Wrap - - - - - - - Second picture: Clip

    enter image description here

    Maybe this issue can be fixed with layoutIfNeeded() or i don't know. Clip is fine for me

    UPDATE (2019.03.27)

    Umm.. I realised that the problem occurs still... I don't understand why.

    Still trying to figure it out..