Problem creating checklist (similar to TouchCells sample code) app for iPhone. Random cells get checked

StackOverflow https://stackoverflow.com/questions/1619407

  •  06-07-2019
  •  | 
  •  

Question

I've been having a problem creating a checklist in the style of the TouchCells example from the Apple sample code. Basically, it is a table that allows multiple selection of its items and gives each selected item a check mark.

The problem I'm having is that when I select an item and then scroll down the screen, another item (off the screen) will randomly be selected. It seems that it is usually the next cell to be loaded on the screen.

I couldn't figure out what I was doing wrong so I tested it with Apple's TouchCells code. In their program though, they only have 6 cells and there is no room to scroll. So, I duplicated some of the items from the plist file to make more cells and... the same problem pops up. If you select a cell and then scroll, another cell will randomly be selected.

Update I recently tried the iPhone Dev Cookbook sample code named "Checks" and... you guessed it, the same problem. Here's the link: http://code.google.com/p/cookbooksamples/downloads/list

This is driving me nuts. Is it a bug or am I doing something wrong? Does anyone know how to fix this?

Thanks!

Also, does anyone know of any sample code that shows how to do this?

Was it helpful?

Solution

I'm having a similar issue with a custom UITableViewCell in my app. According to the Apple docs on prepareForReuse: "you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state."

The TouchCells example is related to selection state, but they are using a boolean and images to simulate selection. So far, the only thing that I have found to work is to use a unique reuse identifier for each cell. Kinda defeats the purposes of reuse, doesn't it?

For example, to resolve the issue in the TouchCells example, replace:

static NSString *kCustomCellID = @"MyCellID";

with:

NSString *kCustomCellID = [NSString stringWithFormat:@"MyCellID%d", indexPath.row];

I guess this is ok if you have a small number of cells, but there's got to be a better way, right?

OTHER TIPS

You are probably doing this:

if (whatever) {
  cell.accessoryType = UITableViewCellAccessoryCheckMark;
}

When you should do this:

if (whatever) {
  cell.accessoryType = UITableViewCellAccessoryCheckMark;
} else {
  cell.accessoryType = UITableViewCellAccessoryNone;
}

If you are using a custom cell, you can override prepareForeReuse:

- (void)prepareForReuse {
  [super prepareForReuse];
  self.accessoryType = UITableViewCellAccessoryNone;
}

Found the solution after a painful late night search...

In the checkAction function in CustomCell.m (referring to the TouchCells example) use setBackgroundImage rather than setImage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top