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 visi开发者_开发技巧ble 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,
TeeMake 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.
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.
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.
精彩评论