views:

75

answers:

1

Hello guys,

I have TableCellViewController for managing cells in my UITableView. Each cell has a label na UISwitch (dictTypeSwitch). A want to assign method to switch events so I can save the state of button.

So far I've done this:

assign setState function to object:

[cell.dictTypeSwitch addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];

function for handling event:

- (void)setState:(id)sender {
    BOOL state = [sender isOn];
    NSString *rez = state == YES ? @"YES" : @"NO";
    NSLog(rez);
}

From sender I get UISwitch object from which I can get state.

So far everything is ok.

But if I want to save the state of UISwitch, I have to get rowIndex for this cell. How can I achieve this?

The cells are made inside function cellForRowAtIndexPath. Se the code bellow:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"DictionariesTableCellViewController";
    DictionariesTableCellViewController *cell = (DictionariesTableCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DictionariesTableCellViewController" owner:nil options:nil];

        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (DictionariesTableCellViewController *) currentObject;
                break;
            }
        }
    }

    // Configure the cell...

    cell.dictTypeLabel.text = [NSString stringWithFormat:@"row - %i",indexPath.row];
    [cell.dictTypeSwitch addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

Thanks

+1  A: 

You can use the UISwitch's .tag property to store an arbitrary integer. This can be set to the row index.

If it is possible to find the UITableViewCell from UISwitch's parent, you could get the index path with

NSIndexPath* indexPath = [theTableView indexPathForCell:theCell];
KennyTM
Thanks Kenny...
borut-t