UITableViewCell - constraints only updated after reload

el-flor picture el-flor · Feb 10, 2017 · Viewed 9.1k times · Source

I have a custom UITableViewCell in which I have a UIView that contains multiple subviews. Depending on the cases, I hide some of those views, and I update constraints so that the parent UIView is still centered in my UITableViewCell.

My issue is that, because of the cell reuse, this only works if the cell isn't directly shown (if the cell isn't one of the top cells that appear first in the table). In such cases, when I scroll down, and I scroll back up, it works again. Pictures will help me explain this:

This is what is displayed once the UITableView is loaded for the first time. The first cell is a regular cell with all info, the second cell is the one where the first elements have been hidden.

First view

This is what happens when I scroll down, and then back up.

enter image description here

As you can see, that's exactly what I want. The constraints have been updated correctly, but only once the cell disappeared from the visible screen, and appeared again.

[reviewsAndPriceView setNeedsUpdateConstraints];
[reviewsAndPriceView setNeedsLayout];
[reviewsAndPriceView layoutIfNeeded];
[self updateConstraints];
[self setNeedsUpdateConstraints];
[self setNeedsLayout];
[self layoutIfNeeded];

And all kinds of variations, but it doesn't work. What's the way to achieve this?

Answer

Kedar Desai picture Kedar Desai · Jul 17, 2017

I had the same issue. I resolved it by calling cell.layoutIfNeeded() before returning cell in cellForRowAtIndexPath. Now, for me its working fine.