Reputation: 44312
I've created a class that contains all UITableView protocol methods. I'm using it successfully in a ViewController that has a tableview on its scene.
The advantage to having all of the tableview code in a different class is that I should be able to unit test tableview methods. The problem I'm running into is that when I call cellForRow(at:)
, it returns a nil
cell.
I can put a breakpoint in the tableview class's cellForRow(at:)
and see just before it return cell
that the cell is valid. Once I leave cellForRow(at:)
and go back into the unit test, the returned cell is nil.
This happens because none of the cells are visible. This thread [ Table view's `cellForRow(at:)` is `nil` in Unit Test ] hits on the problem but not solution for this specific case.
Is there some way to return a cell from cellForRow(at:)
when the tableview/cells are not visible?
Upvotes: 0
Views: 1280
Reputation: 477
UITableViewCell will process appearance calculation in the delegate tableView(_:cellForRowAt:)
, so you may want get the cell it doesn’t definite.
I have met this question recently, and my solution is following:
Definite a global variable (2D-Array) in this or another file:
class ThisTableCell
{
static var cells = [UITableViewCell](repeating: [UITableViewCell](repeating: UITableViewCell(), count: sectionCount), count: rowCount)
}
And then add
ThisTableCell.cells[indexPath.section][indexPath.row] = cell
in that delegate.
And you can type ThisTableCell.cells[indexPath.section][indexPath.row]
to get current Cell.
Upvotes: 0
Reputation: 8978
Your assumption is correct, UITableView.cellForRow(at:)
method doesn't return a cell if it's not visible at that moment.
In the meanwhile why not use the data-source of the UITableView and call UITableViewDataSource.tableView(_:cellForRowAt:)
? I think it does exactly what you need and returns cells disregarding the actual UITableView
position.
Upvotes: 2