How to get all cells in a UITableView

I don't think thats possible, simply because the tableView doesn't store all cells. It uses a caching mechanism which only stores some cells, that are not visible, for reuse.

Why do you need all cells? Maybe you can achieve, what you're trying to do, otherwise.


Here is the simplest solution in Swift 3.0

func getAllCells() -> [UITableViewCell] {

    var cells = [UITableViewCell]()
    // assuming tableView is your self.tableView defined somewhere
    for i in 0...tableView.numberOfSections-1
    {
        for j in 0...tableView.numberOfRowsInSection(i)-1
        {
            if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {

               cells.append(cell)
            }

        }
    }
 return cells
 }

Each time you create a cell you can add it to a NSMutableArray which you can parse whenever you need:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *Cell = [self dequeueReusableCellWithIdentifier:@"Custom_Cell_Id"];
    if (Cell == NULL)
    {
        Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Custom_Cell_Id"]];
        [Cells_Array addObject:Cell];
    }
}

- (void) DoSomething
{
    for (int i = 0;i < [Cells count];i++)
    {
        CustomCell *Cell = [Cells objectAtIndex:i];
        //Access cell components
    }
}

However, a simpler implementation to get the current cells would be using Set i.e O(1)

/// Reference to all cells.
private var allCells = Set<UITableViewCell>()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Your_Cell_ID") as! UITableViewCell
    if !allCells.contains(cell) { allCells.insert(cell) }
    return cell
}