views:

666

answers:

3

Hey guys,

I have a table view which I'm using for some settings in my app. The tables cells are all default (no customisation at all), and simply contain some text for their label and a UISwitch for the accessory view.

My problem is that I need a reference to the switch so that I know when it has been switched on and off.

Currently I am setting the 'tag' property of the switch to be that of the cell's index within the table (grabbed from [indexPath row] in tableView:cellForRowAtIndexpath:).

This is fine when you only have one Section in your table, but I am now adding a new section. The problem is that they are both 0 based indexed so the switches in each section will end up reusing the tags - which isn't good.

Any suggestions on a better way to achieve this? Thanks.

A: 

For each cell, set a delegate link back to the table view controller, and also some kind of row reference ID - then wire the switch to a cell IBAction method, that calls back to the delegate with the reference ID for that cell.

Kendall Helmstetter Gelner
A: 

What you can do is either have an Array of arrays or a dictionary, key it by the section number (or in case of the array they will be in order of the section numbers), now to retreive a switch all you do assuming you know the section and the row number

UISwitch *switch=[[switchArray objectAtIndex:section] objectAtIndex:row];

or if you have a dictionary

UISwitch *switch=[[switchDictionary objectForKey:section] objectAtIndex:row];
Daniel
+2  A: 

If you know roughly how many sections and rows you will have, like oh, say, not more than 1 million rows per section, just hash the section and row like this:

const int oneMillion = 1000000;

int tag = (section * oneMillion) + row;
slider.tag = tag;

Then, to figure out the section and row, reverse the logic:

int tag = slider.tag;
int row = tag % oneMillion;
int section = tag / oneMillion;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow: row inSection: section];

Now get the slider that is in the cell in that section,row of the table

UITableViewCell *sliderCell = [tableView cellForRowAtIndexPath: indexPath];
UISlider *slider = [[sliderCell.contentView subviews] objectAtIndex: 0];

This assumes the slider is always the only view in the contents of the cell.

This method is a bit longer than some of the other suggestions above, but it keeps you from having to cache references off to the side.

Amagrammer