Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell - constraints only updated after reload

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?

like image 420
el-flor Avatar asked Feb 10 '17 11:02

el-flor


2 Answers

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

like image 93
Kedar Desai Avatar answered Oct 03 '22 00:10

Kedar Desai


You already know that cells are being reused.

When you scroll some cells are using constraint of previous displayed.

To resolve this call an reset method which will reset all constraint to its default value as assigned in xib.

After this method call your method which is responsible for changing height/width.

And in last call only :

 [self layoutIfNeeded];
like image 28
Rahul Avatar answered Oct 03 '22 00:10

Rahul