Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLayoutConstraints update after first tableview presentation

  1. I load a custom UITableViewCell from a xib
  2. I update a NSLayoutConstraint programmatically in cellForRowAtIndexPath

Autolayout and manual change of NSLayoutConstraint works as it should - device size, orientation etc.

BUT: on the very FIRST presentation of the cell the programmatic changes are not displayed.
Changing views and going back updates as expected.

I believe I need to put [self setNeedsUpdateConstraints] somewhere.
I tried all kinds of places (viewDidAppear, didEndDisplayingCell ...)

Where should this go?

Could it be a new cell / reused cell issue?

like image 965
Stephan Avatar asked Dec 07 '25 20:12

Stephan


1 Answers

So, to sum things up - this is what I did in order to get nicely laid out views every time:

The UIView is now responsible for itself, no messing around in the tableviewController.

I did not need to call (void)updateConstraints anywhere which makes sense since I set up the constraints in IB and just added a property to be able to change a constant. The actual constraints were left untouched and just needed layout!

  1. Moved all layout code to my UITableViewCell subclass, named it (void)updateMedian (just two lines of code).
  2. Made a property to pass information (a basic float) needed for recalculation of label position into subclass.
  3. Used (void)updateMedian in (void)layoutSubviews of the UITableViewCell subclass to update my coordinates.
  4. Also added a call to (void)updateMedian and [self layoutIfNeeded] in (void)prepareForReuse in my subclass.
  5. Added [cell setNeedsLayout]; [cell layoutIfNeeded] in cellForRowAtIndexPath in my tableviewController.

I guess, the last step makes for a little redundancy. But otherwise there were still some cells that were displaying incorrectly.

like image 192
Stephan Avatar answered Dec 10 '25 12:12

Stephan