Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView cellForRowAt vs willDisplay

I'm a little frustrated. I have a iOS 10 project UITableView with UITableViewAutomaticDimension cells. I set constraints properly.

Initially I was mapping my cells inside

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

and everything was working fine, but then I read an article: https://medium.com/ios-os-x-development/perfect-smooth-scrolling-in-uitableviews-fd609d5275a5#.4rnbc4vyg and moved my data mapping to

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)

after this my auto layout cells stopped to work properly.

My understanding that at height is calculating after cellForRowAt but before willDisplay, so when I'm mapping in willDisplay height is already set for my cell and I need to reload it again (which is not good).

Anyone can proof/explain this?

UPDATE:

After posting a question, I found this article: https://tech.zalando.com/blog/proper-use-of-cellforrowatindexpath-and-willdisplaycell/

like image 436
AlexZd Avatar asked Mar 07 '17 13:03

AlexZd


1 Answers

Always set up your cell inside func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

Apple documentation says about cellForRowAt:

Asks the data source for a cell to insert in a particular location of the table view.

tableView(_:cellForRowAt:)

willDisplay on the other can be used to override certain properties of a cell just before it is drawn to view. I would suggest if you are not sure about willDisplay just do all your set up in cellForRowAt.

Apple's doc says about willDisplay:

This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color.

More on willDisplay is here in Apple's documentation: tableView:willDisplayCell:forRowAtIndexPath:

EDIT: After reading the link you provided - I reaffirm that unless you really have a specific reason to setup your cell in willDisplayCell, just do it in cellForRowAt.

like image 51
Salil Junior Avatar answered Sep 18 '22 21:09

Salil Junior