Reputation: 17169
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?
Upvotes: 2
Views: 10572
Reputation: 2382
for (UIView *view in TableView.subviews) {
for (tableviewCell *cell in view.subviews) {
//do
}
}
Upvotes: -2
Reputation: 17169
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.
Upvotes: 3
Reputation: 3055
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.
Upvotes: 6