Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom action:@selector to UISwitch on TableViewCell

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

like image 253
Borut Tomazin Avatar asked Jul 08 '10 18:07

Borut Tomazin


1 Answers

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];
like image 54
kennytm Avatar answered Oct 11 '22 18:10

kennytm