views:

74

answers:

3

Hi,

I'm trying to toggle the color of UITableCell when it is clicked.
Code is below

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    RowCell *cell = (RowCell*) [tableView cellForRowAtIndexPath:indexPath];
    [cell toggle];
}

The toggle actually works, except that it seems like it hilight more than 1 cell.
i.e if 10 rows covers the currently visible area, clicking on the first row will hilight row 1, row 11, row 21 etc instead of just row 1 that I clicked.

How can I prevent that from happening?

Thanks,
Tee

+1  A: 

Make sure that you are properly configuring your cells in tableView:cellForRowAtIndexPath:. Remember, by using dequeueReusableCellWithIdentifier: you are reusing table view cells. The cell at row 11 is probably the same cell that was previously shown at row 1.

Set the highlight state of each cell before it is returned by tableView:cellForRowAtIndexPath:. Note that this will probably require you to store the highlight state of each row somewhere other than in the cells themselves.

James Huddleston
Also consider using tableView:willDisplayCell:forRowAtIndexPath:, as suggested in other answers. Apple says it's for changing "state-based properties set earlier by the table view, such as selection and background color, and not content." If changing the background color of your cell is a "table thing" and doesn't get reflected in your data model, tableView:willDisplayCell:forRowAtIndexPath: seems more appropriate than tableView:cellForRowAtIndexPath:. Either method should work, though.
James Huddleston
A: 

Since cells are reused, implement tableView:willDisplayCell:forRowAtIndexPath: and set the toggle to the desired value. Of course you must store in your model the state of the toggle button for each cell.

Marco Mustapic
A: 

Remember, cells are reused. So when this cell is handed back to you in dequeueReusableCellWithIdentifier:, it will still be toggled (and you're probably not changing it back). Rather than calling a method on the cell, you should call a method on the underlying data object that you use to provide data to the cell. Then in tableView:willDisplayCell:forRowAtIndexPath:, you should do final display cleanup like what "toggle" probably does.

Rob Napier