luis.mazoni
luis.mazoni

Reputation: 1092

UILabel not respecting contraints after scrolling (label inside a xib, dequed as a uitableviewcell)

This is the craziest problem I've ever faced in iOS development. Basically I have a xib file: xib file

This xib file is loaded as a row in a UITableView. In this xib file I have an UILabel ("Texto do comentário"), that is a multiline uilabel and will expand according to its content. To do so, I've added the following constraints and content hugging:

constraints

And all this actually works fine when I run and replace the content with a big text. This is how it looks like:

working fine

OK, now it begins the weird things, if I scroll up to the other cell (that uses the same xib file), the text view expanded its width and height in a way that doesn't respect my constraints:

upper cell is weird

Now if I scroll back to my cell that was working fine before, it has the same problem, the uilabel's width and height are not respecting my constraints anymore:

cell that was working fine, now is not

I've tried to inspect what actually happens to the constraints, if they are being ignored by some reason, and here is what I've found out. Both the constraints of my uilabel that has the right size and the ones in the uilabel that has the wrong size are the same.

fine uilabel constraints wrong uilabel constraints

I'm really starting to thing that this an iOS bug. Thank you in advance for your help

Upvotes: 2

Views: 451

Answers (3)

Dex
Dex

Reputation: 971

This looks like another bug I previously encountered with self-sizing cells in a table view. Originally, I worked around it by explicitly setting the preferredMaxLayoutWidth of my cell's labels but I then discovered that sending an -updateConstraintsIfNeeded message to my cell in -tableView:cellForRowAtIndexPath: also worked around the issue without needing to set the preferredMaxLayoutWidth.

Hope this helps.

Upvotes: 0

Catalina T.
Catalina T.

Reputation: 3494

I would say the problem you have is that you changes the Content Hugging Priority and Content Compression Resistance Priority values, which will make the UILabel not resize as you would expect.

You could try resetting the values to the default ones and if your other constraints are correct, the height of the label and of the cell should be calculated correctly.

enter image description here

Probably the UITextView worked because you did not change the default values for these properties.

Hope this helps.

Upvotes: 1

luis.mazoni
luis.mazoni

Reputation: 1092

After trying, at least everything. The fix I found is to use UITextView instead of UILabel. This fix made me be sure that this is a UILabel bug.

Upvotes: 1

Related Questions