Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference heightForRowAt vs estimatedHeightForRowAt?

Normally when i want set my row height then set

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 300
    }

what is the benefited with estimatedHeightForRowAt when should i use it.

update! if i want to set estimatedHeightForRowAt:

 func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

        return // what should i put here
    }

UPDATE:
Is there any effect tableview scrolling if i provide as my wish estimatedHeightForRowAt? . for example i give in estimatedHeightForRowAt 500

like image 381
cristainlika3 Avatar asked Mar 08 '23 13:03

cristainlika3


2 Answers

As specified in the iOS documentation:

If the table contains variable height rows, it might be expensive to calculate all their heights and so lead to a longer load time. Using estimation allows you to defer some of the cost of geometry calculation from load time to scrolling time.

like image 131
Andrea Gottardo Avatar answered Apr 30 '23 17:04

Andrea Gottardo


This difference becomes more meaningful when you have some custom cells which their height is different from most of your other cells. In that case the OS use estimatedHeightForRowAt as a default (This optimizes your loading time), but then if specified a different height for a row then it would use that.

As for what to put there:

If there is no variation then you put the same 300. Basically you put your default/most expected height there. For the heightForRowAt depending on your needs you may want to do switch based on section/row and change height. If don't have any variations then still just put 300 there


I'm not sure if this is why you asked or not, but if you were asking this because you had dynamic tableViewCells with different heights, then the solution is:

  1. Use Auto Layout when creating your table view cells.
  2. Set the tableview rowHeight to UITableViewAutomaticDimension.
  3. Set the estimatedRowHeight or implement the height estimation delegate method.

Basically do:

override func viewDidLoad() {  
    super.viewDidLoad()

    self.tableView.estimatedRowHeight = 80 // or any other number that makes sense for your cells
    self.tableView.rowHeight = UITableViewAutomaticDimension
}

For more see this RW Tutorial and this high voted question


NOTE

If you don’t give the estimatedRowHeight then tableview will dequeue a lot more cells, because it’s trying to be smart and needs to prepare itself for smooth scrolling. It will trigger both your cellForRow & willDisplay callbacks

If you give estimatedRowHeight a value, then it won’t dequeue cells offscreen anymore

like image 41
mfaani Avatar answered Apr 30 '23 17:04

mfaani