Reputation: 675
How do I get the cell for an indexPath which is not currently visible in the table? (cell is out of range)
Code for getting my cell:
NSString *name = [[(ELCTextfieldCell *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]] rightTextField] text];
-cellForRowAtIndexPath...
returns nil
because the cell at the required indexPath is out of range. So how do I get the correct cell and not nil?
Upvotes: 10
Views: 12254
Reputation: 201
In continue to @Raphael's answer, Here is the (working) swift 3 solution:
UITableViewCell cell = self.tableView(self.tableView, cellForRowAt: indexPath)
Upvotes: 1
Reputation: 45088
UITableViewCells are made to be reused/recycled in a way that the users won't need to create more cells than the number of visible ones. You usually don't need to access a cell that is not visible. It should be enough you access your datasource and get/set the correspondent data there. Cells are for showing some state of the datasource. Not the datasource itself :)
Edit:
You said you need some information (text) from one cell above, right? If you use cellForRowAtIndexPath:
method the cell will be recreated but you might not get the text that was in the textfield. The reason? because probably you didn't save it somewhere else. If you did save it, then access that directly instead of going through the cell.
Upvotes: 2
Reputation: 4214
Is the information to fill your table coming from an array? Could you not pull that directly out of the array at 0 index, same as your cellForRowAtIndexPath would presumably retrieve and fill that cell when it is displayed?
Upvotes: 0
Reputation: 25632
This is not how it works. You need to grab and store the information as soon as it is entered or changed. It may easily get out of scope and you cannot guarantee your cell lives long enough. Well, technically you can hold onto it (and always return the very same cell for the same index path), but I'd question that design.
Upvotes: 5
Reputation: 3870
The UITableView
only keeps the visible cells. If you need one that isn't visible you have to call the tableView:cellForRowAtIndexPath:
of the UITableView
dataSource
. So, if self is a class that is the dataSource
:
UITableViewCell * cell = [self tableView:table cellForRowAtIndexPath:indexPath];
Upvotes: 17