2

I have a UITableView with limited number of rows (let's say 20-30). Is it possible to disable cell reuse?

Most of solutions propose not to call dequeueReusableCellWithIdentifier. But in this case every time UITableViewSource needs new cell - new instance of that cell is created.

What I want is once I scrolled all the way down and saw all 20-30 cells, on my way back no new cell should be created.

Is it possible?

Community
  • 1
  • 1
Mando
  • 11,414
  • 17
  • 86
  • 167
  • Why do you want to disable cell reuse? – rdelmar Oct 12 '14 at 20:27
  • @rdelmar - one use case is if the cell is being used to hold state, which will be read when done with the view. For example, a cell containing a switch. The initial switch state is set from a data source. The user toggles the switch. But the user action is not committed until Done/Cancel actions for the view as a whole. Without a cell that can hold state, it is more complex: must create a second copy of backing data to hold the state changes. – ToolmakerSteve Jul 12 '16 at 19:48

2 Answers2

3

Even if you use unique identifiers, you can't rely on the reuse pool size being large enough to store the 20-30 unique cells that you are trying to do.

You will need to hold your own reference to your cells, in an array or dictionary, and use this to obtain the cell in cellForRowAtIndexPath - For example -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier=[NSString stringWithFormat:@"Cell%d",indexPath.row];

    UITableViewCell *cell=self.cellDictionary[cellIdentifier];

    if (cell == nil) {
          cell=[[MyCell alloc]init];  // Do whatever is required to allocate and initialise your cell
          self.cellDictionary[cellIdentifier]=cell;
    }

    // Any other cell customisation

    return cell;
}

Unless cell creation is very expensive then re-use is typically a better approach

Paulw11
  • 108,386
  • 14
  • 159
  • 186
1

I believe you could just assign each cell a unique reuse identifier (just a string based off the index path and row).

Aaron Wojnowski
  • 6,352
  • 5
  • 29
  • 46
  • i just verified because it sounds like a solution but unfortunately after I receive null from dequeueReusableCellWithIdentifier by let's say CELL_KEY_23 (where 23 is indexPath.Row) method it is not registered anywhere and next time I call dequeueReusableCellWithIdentifier with the same key (CELL_KEY_23) it returns null again. – Mando Oct 12 '14 at 20:09
  • this approach does not work AFAIK - I tried several variations without success (holding on to the cells in my own array). If someone can make this work, I'd like to see the details. – ToolmakerSteve Jul 12 '16 at 19:56