Get all cells In UITableView?

10,409

Solution 1

Are you re-using table cells in your implementation? If so, i think you cant get all the UITableViewCell objects from your UITableView because of the cell re-use logic of UITableView.

Therefore you'd need to "disable" the cell re-use mechanics in your code. This can be accomplished by not dequeueing (i.e. not using the dequeueReusableCellWithIdentifier method anymore) your cells inside the cellForRowAtIndexPath method of your table view data source delegate and by passing nil for the reuseIdentifier property for the cell init method (initWithStyle:reuseIdentifier:).

Then your allTableViewCellsArray method could probably work! But i think you're still not going to have any luck accomplishing this.

from the Apple docs for [tableView cellForRowAtIndexPath:]:

Return Value

An object representing a cell of the table or nil if the cell is not visible or indexPath is out of range.

Solution 2

Found a solution. Rather than grabbing all the cells at any point in time I choose, as it doesn't work; I create an array of all the cells as they are made, this way every cell is iterated through meaning I can add them all into an array.

I do this in the willDisplayCell method.

Share:
10,409
Josh Kahane
Author by

Josh Kahane

Updated on June 04, 2022

Comments

  • Josh Kahane
    Josh Kahane almost 2 years

    I need to get an array of all the cells in my UITableView. I currently use the method below:

    -(NSArray *)allTableViewCellsArray
    {
        NSMutableArray *cells = [[NSMutableArray alloc] init];
    
        for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
        {
            for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
            {
                [cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
            }
        }
    
        return cells;
    }
    

    I've had some success with it, however I have come to discover it crashes when a cell isn't visible. So how can I get an array of all the cells in my UITableView regardless as to whether they are visible or not?